I have a Spring controller annotated with @RestController
and it is returning JSON. I also have a class annotated with @ControllerAdvice
with @ExceptionHandler
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.
If I use an @ExceptionHandler(Exception.class)
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.
- 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?
- How can I turn off returning HTML entirely and ensure only JSON responses no matter whether the request has an exception or not?