I have a spring boot application with restful endpoints. I want to have a global error handler that basically traps any exceptions so that I can then manage the response (i.e. dont want to expose a big java stacktrace in the response)
Whats the best way to achieve this?
Create a controller advice class with an exception handler that will cache all exceptions of your desired type.
@ControllerAdvice
public class GlobalExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Exception.class)
public void handleAll(Exception e) {
log.error("Unhandled exception occurred", e);
}
}
If you like, you can return a body from the method just like from a regular controller method or simply return some HTTP status code. The above code returns 500 using the @ResponseStatus annotation.
You can catch only specific exception types. The @ExceptionHandler annotation accepts an array of exceptions as the value attribute.