---
title: "Better exception responses in Rails 5 API apps"
description:
  "Rails 5 responds with proper responses to exceptions even for API apps with
  introduction of new configuration debug_exception_format."
canonical_url: "https://www.bigbinary.com/blog/better-exception-responses-in-rails-5-api-apps"
markdown_url: "https://www.bigbinary.com/blog/better-exception-responses-in-rails-5-api-apps.md"
---

# Better exception responses in Rails 5 API apps

Rails 5 responds with proper responses to exceptions even for API apps with
introduction of new configuration debug_exception_format.

- Author: Akshay Mohite
- Published: March 3, 2016
- Categories: Rails 5, Rails

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](https://github.com/rails/rails/pull/20831) to respond with
proper format for exceptions.

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

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

```bash
$ 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.

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

## Links

- [Human page](https://www.bigbinary.com/blog/better-exception-responses-in-rails-5-api-apps)
