Adding sentry.io
is quite straightforward, however adding it when the project is already in advanced state is not that simple as you have to send each exception to sentry.io. According to some different posts, it’s simply not possible. However I came up with something that might work for you as well.
The setup
This particular project is a REST API, where ResponseStatusException
are thrown in case something goes wrong. Next is an example:
throw new ResponseStatusException(HttpStatus.CONFLICT, "not eligable");
Out of the box, Spring Boot transforms these exception to a proper response.
It is important that ResponseStatusException
is used consistenly in your REST controllers when things go south.
The Workaround
Exceptions can be handled with the very aptly named @ExceptionHandler
and @ControllerAdvice
annotations.
@ControllerAdvice
is an AOP annotation making sure that this code in interweaved with the controllers@ExceptionHandler
works as a listener/subscriber. You provide the exception it will handle (in this exampleResponseStatusException
) and the annotated method acts on it (hence the method has aResponseStatusException
parameter)
@ControllerAdvice
public class SentryExceptionHandler {
@ExceptionHandler(ResponseStatusException.class)
protected ResponseEntity<String> handleException(ResponseStatusException ex) {
Sentry.captureException(ex);// send to sentry
return ResponseEntity
.status(ex.getStatus())
.body(ex.getReason());
}
}
Once we act on the ResponseStatusException
, we still need to create a response with the same status code and reason as the incoming ResponseStatusException
. While checking the @ExceptionHandler
Javadocs,I learned the method handling the exception can return a ResponseEntity
which is ideal for passing along the status code and the message.