Return JSON on uncaught exceptions in Spring controllers
<p>I have a Spring controller annotated with <code>@RestController</code> and it is returning JSON. I also have a class annotated with <code>@ControllerAdvice</code> with <code>@ExceptionHandler</code>s related to some custom exceptions. I am using Tomcat to serve this RESTful API. I'd like to have any non-custom exception such as one coming from a 3rd party library or a NullPointerException be caught and returned with status 500 - Internal Server Error as JSON with a message instead of an HTML page showing the error.</p>

<p>If I use an <code>@ExceptionHandler(Exception.class)</code> in the controller advice it takes over all of Spring exceptions like MissingPathVariableException.class, which is not ideal. I've tried extending Spring's ResponseEntityExceptionHandler but this class is not annotated with @ResponseBody so does not return JSON.</p>

<ol>
<li>How do you return JSON for uncaught and unknown exceptions (ones you can't plan for) in a Spring RESTful API without influencing Spring's internals?</li>
<li>How can I turn off returning HTML entirely and ensure only JSON responses no matter whether the request has an exception or not?</li>
</ol>