title: how to handle exceptions in JSON based RESTful code?
body: <p>I have a "software as a service" app that uses JSON communicated via a RESTful API.  </p>
  
  <p>Simply stated: what are the best practices for capturing and reporting exceptions when using a RESTful API with JSON data interchange?</p>
  
  <p>My first thought was to see what Rails does by generating a scaffold, but that's clearly not right.  Here's an excerpt:</p>
  
  <pre><code>class MumblesController &lt; ApplicationController
  
    # GET /mumbles/1
    # GET /mumbles/1.json
    def show
      @mumble = Mumble.find(params[:id])
      respond_to do |format|
        format.html # show.html.erb
        format.json { render json: @mumble }
      end
    end
  
  end
  </code></pre>
  
  <p>In this case, if the JSON code sends a non-existent ID, e.g.</p>
  
  <pre><code>http://www.myhost.com/mumbles/99999.json
  </code></pre>
  
  <p>then Mumble.find() will raise ActiveRecord::RecordNotFound.  ActionController will catch that and render an error page in HTML.  But HTML is useless to the client that is expecting JSON.</p>
  
  <p>I could work around that by wrapping the Mumble.find() in a <code>begin ... rescue RuntimeError</code> block and rendering a JSON status => :unprocessable_entity or something.</p>
  
  <p>But then what if the client's app sends an invalid path, e.g.:</p>
  
  <pre><code>http://www.myhost.com/badtypo/1.json
  </code></pre>
  
  <p>Is a JSON based app supposed to catch that and return an error in JSON?  If so, where do I capture that without digging deep into ActionDispatch?</p>
  
  <p>So overall, do I punt and let ActionController generate HTML if there's an error?  That doesn't feel right...</p>