12

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

2 Answers 2

25

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!

3
  • 3
    Also, check out Sinatra's halt. Nov 5, 2013 at 21:20
  • 3
    If you use halt(404) as suggested by Jordan, not_found will be automatically called (and you don't even need to specify the status directive).
    – Alessandro
    Apr 24, 2014 at 18:27
  • 2
    However, note that in my experience - contrary to what the original answer is suggesting - not_found only catches 404s. It won't be invoked for 500s or even other errors in the 4xx class.
    – Alessandro
    Apr 24, 2014 at 18:28
2

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.

2
  • Unfortunately all pages now raise 404
    – olimart
    Nov 5, 2013 at 14:59
  • Check to see what requested_erb = File.join(root, 'pages', params[:page]) returns - this may not be 100% correct.
    – CDub
    Nov 5, 2013 at 15:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.