![](/img/trans.png)
[英]How to catch the exceptions thrown by spring security matchers?
[英]In a Spring Boot application, how would I catch internally thrown exceptions that would otherwise escape to the client, but not Spring MVC exceptions?
我的Spring Boot应用程序中有一个类,该类使用@ControllerAdvice自动处理许多特定的异常:
@ControllerAdvice
@RequestMapping(produces = APPLICATION_JSON_UTF8_VALUE)
public class RestResponseEntityExceptionHandler {
例如,我抓住了这个:
@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);
}
甚至是低级数据库异常:
@ExceptionHandler(DataIntegrityViolationException.class)
public ResponseEntity<ErrorDTO> dataIntegrityViolationException(final DataIntegrityViolationException e) {
但是有时候,有些异常会转交给我没有专门处理并且不知道的异常。 在日益复杂的应用程序中,我无法预测所有异常的名称。
所以我天真地添加了这个:
@ExceptionHandler(Exception.class)
protected ResponseEntity<ErrorDTO> exception(final Exception e) {
ErrorDTO error = new ErrorDTO(
"Test", "test");
return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
}
但这涵盖了所有内容,甚至包括Spring MVC异常。 因此,现在,如果我向某个不存在的端点发出请求,并且通常Spring MVC可以很好地处理此请求,那么它现在也陷入了我的方法中,我不希望这样。
我该怎么做,以便在控制器中的入口点之后发出的所有异常都被捕获在这里,从而使客户端永远不会看到堆栈跟踪,但是Spring MVC甚至在输入我的代码之前所处理的所有事情都可以正常处理?
如果需要常见错误消息,可以尝试在ControllerAdvice上扩展ResponseEntityExceptionHandler并覆盖handleExceptionInternal。 我相信您必须将某些内容添加到应用程序属性中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.