title: How to catch exceptions in grails REST controllers
body: <p>If you use a controller to implement rest APIs, you want to deal with any exception thrown and return a generic or specific well formed REST response.</p>
  
  <p>We can't use global error URL mapping method, as the application has a number of APIs and interfaces with different response requirements, and we also don't know which type of Grails' HTTP error codes will be thrown (e.g don't know if it will be a 400, 422, 500 etc).  Also, if we used the error page mappings, we won't be able to put relevant data into the JSON response.</p>
  
  <p>E.g. this will generate a GrailsRuntimeException:</p>
  
  <pre><code>class SomeController {
      def payload = request.JSON
      def someMethod() {
          BigDecimal x = new BigDecimal(payload.notExists)
      }
  </code></pre>
  
  <p>The problem is, it seems impossible to catch any error thrown.</p>
  
  <p>E.g. neither this approach:</p>
  
  <pre><code>def handleRuntimeException(RuntimeException e) {
        render("some JSON error message")
  }
  </code></pre>
  
  <p>Nor this approach:</p>
  
  <pre><code>try {
      :
  }
  catch (GrailsRuntimeException e) {
          render("some JSON error message")
  }
  </code></pre>
  
  <p>Works - it never catches the error.</p>
  
  <p>Tried GroovyRuntimeException, Exception, MissingMethodException, Throwable etc.</p>
  
  <p>The only solution we can think of is to not do any work in the controller, do everything in a service, where apparently we can catch errors.</p>
  
  <p>This approach:</p>
  
  <pre><code>static mappings = {
      "500"(controller: "error")
  }
  </code></pre>
  
  <p>Is not want we need for several reasons:</p>
  
  <ol>
  <li>We have several different APIs in different controllers which would require different response formats.</li>
  <li>we also have UI controllers, which would want the default error system which shows the stack trace etc.</li>
  <li>We want to handle the error in the controller where the exception happened, so we can clean up, or at least can log or return the stat which only the controller knows.</li>
  </ol>
  
  <p>Have decided the only way is to move all code into services, and do nothing in the controller except pass the request, and render the resultant string.  i.e. all parameter handling, especially number conversion, is done in the service. </p>