简体   繁体   中英

In a Spring Boot application, how would I catch internally thrown exceptions that would otherwise escape to the client, but not Spring MVC exceptions?

I have a class in my Spring Boot application that handles many specific exceptions automatically, using @ControllerAdvice:

@ControllerAdvice
@RequestMapping(produces = APPLICATION_JSON_UTF8_VALUE)
public class RestResponseEntityExceptionHandler {

For instance I catch this:

@ExceptionHandler(OptimisticLockingFailureException.class)
public ResponseEntity<ErrorDTO> optimisticLockingFailureException(final OptimisticLockingFailureException e) {
    LOGGER.info("Encountered OptimisticLockingFailureException", e);
    ErrorDTO errorDTO = new ErrorDTO("CONFLICT_ERROR", "Object was locked by ano user, please refresh and try again.");
    return new ResponseEntity<>(errorDTO, HttpStatus.CONFLICT);
}

And even low level database exceptions:

@ExceptionHandler(DataIntegrityViolationException.class)
public ResponseEntity<ErrorDTO> dataIntegrityViolationException(final DataIntegrityViolationException e) {

But sometimes still some exceptions escape to the client that I didn't handle specifically and didn't know about. I cannot predict the names of all exceptions in an increasingly complex application.

So I naively added this:

@ExceptionHandler(Exception.class)
protected ResponseEntity<ErrorDTO> exception(final Exception e) {
    ErrorDTO error = new ErrorDTO(
            "Test", "test");
    return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
}

But this catches everything, even Spring MVC exceptions. So now if I do a request to some non-existing endpoint and normally Spring MVC handles this nicely, it now also is caught in my method and I don't want that.

How would I make it so all exceptions emitted after the entry point in my controllers are caught here so that the client never sees a stacktrace, but everything that Spring MVC handles before my code is even entered is handled normally?

You can try extending ResponseEntityExceptionHandler on your ControllerAdvice and overriding handleExceptionInternal if you need to have a common error message. I believe there are some things you would have to add to your application properties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM