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

rails-api, ruby, ruby-on-rails

Solution

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.

Problem

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?

Original source