Last Updated: September 29, 2021
·
11.17K
· luizhrqas

Setting Rails 4 HTTP Errors in JSON response

If you need for some reason to output your Rails 4 Errors in JSON format, here is the snippet.

You need to put this in your "ApplicationController" (or in the main controller of your namespace, usually the ApiController):

# CUSTOM EXCEPTION HANDLING
 rescue_from Exception do |e|
   error(e)
 end

 def routing_error
   raise ActionController::RoutingError.new(params[:path])
 end

 protected

 def error(e)
   #render :template => "#{Rails::root}/public/404.html"
   if env["ORIGINAL_FULLPATH"] =~ /^\/api/
   error_info = {
     :error => "internal-server-error",
     :exception => "#{e.class.name} : #{e.message}",
   }
   error_info[:trace] = e.backtrace[0,10] if Rails.env.development?
   render :json => error_info.to_json, :status => 500
   else
     #render :text => "500 Internal Server Error", :status => 500 # You can render your own template here
     raise e
   end
 end

1 Response
Add your response

You can rewrite the error method like this :)
ruby def error(e) # render :template => "#{Rails::root}/public/404.html" return raise e unless env['ORIGINAL_FULLPATH'] =~ %r{^/v\d/} error_info = { error: 'internal-server-error', exception: "#{e.class.name} : #{e.message}" } error_info[:trace] = e.backtrace[0, 10] if Rails.env.development? render json: error_info.to_json, status: 500 end
As you can see it avoids the use of an if else making its execution a bit faster :+1:

over 1 year ago ·