Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define global error handler for JSON in Sinatra

Tags:

ruby

sinatra

I would like to define an error block (or something) that would return all exceptions formatted in JSON somehow plus returning the standard http code (e.g. 404 for not found, 303 for auth errors etc).

Something like:

error do
  e = env['sinatra.error']
  json :result => 'error', :message => e.message
end

Thanks!

like image 935
lzap Avatar asked Oct 19 '25 14:10

lzap


1 Answers

This should work:

require 'sinatra'
require 'json'

# This is needed for testing, otherwise the default
# error handler kicks in
set :environment, :production

error do
  content_type :json
  status 400 # or whatever

  e = env['sinatra.error']
  {:result => 'error', :message => e.message}.to_json
end

get '/' do
  raise 'hell'
end

Test it with curl to see that it works.

like image 137
Jesse Storimer Avatar answered Oct 22 '25 03:10

Jesse Storimer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!