How do I get exceptions to render a plain text version of the Rails development error page?

2.2k Views Asked by At

I am using rails-api to build an API with no web interface. When I get errors in development, I'd love to see just the error message and stacktrace in plain text without all of the HTML wrapping. How do I override the global exception handling so it renders the stacktrace in development mode in plain text/JSON, and a generic error message in production?

2

There are 2 best solutions below

2
On

I would suggest that including the stack trace in production code is probably not a good idea from a security stand point.

Here is how I would do it:

render :json => {message:exception.message, stack_trace: exception.stacktrace}

I hope this helps.

After Sam's clarification I can add:

In your base controller for your API (probably ApplicationController):

class ApplicationController < ActionController::Base
    ...
    rescue_from Exception do |exception|
        error = {message:exception.message}
        error[:stack_trace] = exception.stacktrace if Rails.env.development?
        render :json => error
    end
    ...
end

Caveat: You may not want to rescue from every single exception in this way but this is how you'd do it if you did.

0
On

Some improvements over @donleyp answer to get a clean trace in Rails 3.2 and output generic error info in production:

class ApplicationController < ActionController::API   
    ...   
    rescue_from Exception do |exception|
        if Rails.env.development?
            error = {message:exception.message}
            error[:application_trace] = Rails.backtrace_cleaner.clean(exception.backtrace) 
            error[:full_trace] = exception.backtrace 
            render :json => error
        else
            render :text => "Internal server error.", :status => 500
        end   
    end
    ...    
end