1

I'm trying to handle errors nicely using Sinatra. For example, say I have a block like this:

get '/auth/' do
    ...
    begin
        access_token_obj = OAuth2::AccessToken.new(client, token)
    rescue OAuth2::Error => e
        return 403, e.description
    rescue
        return 403, "Something went wrong"
    end
    ...
end

I want to display a nice error page to the user. The Sinatra docs suggest I can do something like:

error 403 do
    "Access forbidden"
end

But how do I get the error message ("Something went wrong" or e.description) to display to the user? In my error 403 do block there is no env['sinatra.error'] available. I'm obviously missing something (I'm a bit new to ruby).

1 Answer 1

2

Look in the body variable, you'll have the error message in the first index, so in body[0].

Sign up to request clarification or add additional context in comments.

5 Comments

Within error 403 do? In there, body is an empty array for me.
Strange, I can find it in a 6 lines scripts. Just return inspect instead of "Access forbidden" within error 403 do, and see if you can find anywhere your error message.
Ahh... if I replace the return 403, e.description with return 403, e then I get an OAuth2::Error object in body. But I can't work out how to get the error message out of it.
If I do body.inspect I get this: ` #<OAuth2::Error: {"errors"=>[{"domain"=>"global", "reason"=>"authError", "message"=>"Invalid Credentials", "locationType"=>"header", "location"=>"Authorization"}], "code"=>401, "message"=>"Invalid Credentials"}: {"error":{"errors":[{"domain":"global","reason":"authError","message":"Invalid Credentials","locationType":"header","location":"Authorization"}],"code":401,"message":"Invalid Credentials"}}>`
Well, I'm a bit baffled. I think I'll just replace e.description with "My error message" which I can indeed get out of body[0]. So thanks for that pointer Thomas.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.