Q:

How to stop exception html being returned

I am testing a rails api-only app by sending requests to the development server from a test app.  Sometimes when I generate an exception it triggers an exception that returns a page of html giving details of the exception.  The start of it looks  like this:
<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>Action Controller: Exception caught</title>
  <style>
    body {
      background-color: #FAFAFA;
      color: #333;
      margin: 0px;
    }

This verbose page makes it difficult to see what is happening when looking at the test app. Is there any way to get the api app to return a json response when it hits an exception?

A:

Rails doesn't have any built-in JSON exception format, but you can use rescue_from to catch exceptions and return a response of your choosing:
class ApplicationController < ActionController::API
  rescue_from RuntimeError do |ex|
    render json: { success: false, error: ex.class.name, message: ex.message }, status: 500
  end
end

