In Ruby/Sinatra, how to halt with an ERB template and error message

Viewed 3292

In my Sinatra project, I'd like to be able to halt with both an error code and an error message:

halt 403, "Message!"

I want this, in turn, to be rendered in an error page template (using ERB). For example:

error 403 do
    erb :"errors/error", :locals => {:message => env['sinatra.error'].message}
end

However, apparently env['sinatra.error'].message (aka the readme and every single website says I should do it) does not expose the message I've provided. (This code, when run, returns the undefined method `message' for nil:NilClass error.)

I've searched for 4-5 hours and experimented with everything and I can't figure out where the message is exposed for me to render via ERB! Does anyone know where it is?


(It seems like the only alternative I can think of is writing this instead of the halt code above, every time I would like to halt:

halt 403, erb(:"errors/error", :locals => {m: "Message!"})

This code works. But this is a messy solution since it involves hardcoding the location of the error ERB file.)

(If you were wondering, this problem is not related to the show_exceptions configuration flag because both set :show_exceptions, false and set :show_exceptions, :after_handler make no difference.)

2 Answers

In Sinatra v2.0.7+, messages passed to halt are stored in the body of the response. So a halt with an error code and an error message (eg: halt 403, "Message!") can be caught and rendered in an error page template with:

error 403 do
  erb :"errors/error", locals: { message: body[0] }
end
Related