I have a basic sinatra app that renders files from a directory. What I'd like is returns 404 if page does not exist. Currently it raise 500 error.
get '/:page' do
erb :"pages/#{params[:page]}", layout: :"layouts/application"
end
Try this ;)
# 404 Error!
not_found do
status 404
erb :oops
end
Make yourself a 404 page with whatever name you like (mine is oops.erb
, for example), and this should work just fine.
not_found
is Sinatra's error-handling helper for grabbing error 500s and 404 not-founds that it returns. You can then change the HTTP status and corresponding view using it. Check out the documentation for all of Sinatra's error handler's: they're super useful!
halt(404)
as suggested by Jordan, not_found
will be automatically called (and you don't even need to specify the status
directive).
Apr 24, 2014 at 18:27
not_found
only catches 404s. It won't be invoked for 500s or even other errors in the 4xx class.
Apr 24, 2014 at 18:28
You could do something like:
get '/:page' do
requested_erb = File.join(root, 'pages', params[:page])
pass unless File.exists?(requested_erb)
erb :"#{requested_erb}", :layout: :"layouts/application"
end
I haven't tested this, so there might be some issues with the above code, but that's the general idea in my head.
requested_erb = File.join(root, 'pages', params[:page])
returns - this may not be 100% correct.