This blog is part of our Rails 5 series.

Rails 4.x returns error information in HTML page whenever there is any exception, in the development environment.

This is fine for normal HTML requests. But traditionally, Rails always returned with HTML response for exceptions for all requests, including JSON on XML requests in development.

We can now generate API only apps in Rails 5. In case of such apps, it’s better to have the error message in the format in which request was made. Having an HTML response for a JSON endpoint like http://localhost:3000/posts.json is not going to help in debugging why the exception happened.

New config option debug_exception_response_format

Rails 5 has introduced new configuration to respond with proper format for exceptions.

# config/environments/development.rb
config.debug_exception_response_format = :api

Let’s see an example of the response received with this configuration.

$ curl localhost:3000/posts.json
{"status":404,"error":"Not Found","exception":"#\u003cActionController::RoutingError: No route matches [GET] \"/posts.json\"\u003e","traces":{"Application Trace":[...],"Framework Trace":[...]}}

The status key will represent HTTP status code and error key will represent the corresponding Rack HTTP status.

exception will print the output of actual exception in inspect format.

traces will contain application and framework traces similar to how they are displayed in HTML error page.

By default, config.debug_exception_response_format is set to :api so as to render responses in the same format as requests.

If you want the original behavior of rendering HTML pages, you can configure this option as follows.

# config/environments/development.rb
config.debug_exception_response_format = :default