简体   繁体   English

在Spring Boot应用程序中,我将如何捕获内部抛出的异常,这些异常本来会逃逸到客户端,但不会捕获Spring MVC异常?

[英]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: 我的Spring Boot应用程序中有一个类,该类使用@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. 但这涵盖了所有内容,甚至包括Spring MVC异常。 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. 因此,现在,如果我向某个不存在的端点发出请求,并且通常Spring MVC可以很好地处理此请求,那么它现在也陷入了我的方法中,我不希望这样。

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? 我该怎么做,以便在控制器中的入口点之后发出的所有异常都被捕获在这里,从而使客户端永远不会看到堆栈跟踪,但是Spring MVC甚至在输入我的代码之前所处理的所有事情都可以正常处理?

You can try extending ResponseEntityExceptionHandler on your ControllerAdvice and overriding handleExceptionInternal if you need to have a common error message. 如果需要常见错误消息,可以尝试在ControllerAdvice上扩展ResponseEntityExceptionHandler并覆盖handleExceptionInternal。 I believe there are some things you would have to add to your application properties. 我相信您必须将某些内容添加到应用程序属性中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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