3

如何获取由@ExceptionHanlder 注释的所有异常处理程序并且我可以手动调用它们?

背景
我需要通过我自己的异常处理程序来处理一些异常,但在某些情况下,我处理的异常不是由 spring 直接抛出的,它们被包装在原因中。所以我需要在一个地方使用我自己现有的异常处理策略来处理这些异常引起@ExceptionHandler的。我怎样才能做到这一点?

4

4 回答 4

1

尝试使用 Java Reflection Api 查找带有“ExceptionHanlder”注释的类。并调用任何方法或任何你想要的。

于 2018-07-16T13:52:02.983 回答
0

您可以扩展ResponseEntityExceptionHandler并使其@ControllerAdvise如下所示。

@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler({YourException.class})
    public ResponseEntity<Object> handleMyException(Exception ex, WebRequest request) {
            ... handle the way you like it
            return new ResponseEntity<Object>(YourErrorObject, new HttpHeaders(), HttpStatus);
    }
}
于 2018-07-16T07:16:22.953 回答
0

Spring 提供@ControllerAdvice了可以与任何类一起使用的注释来定义我们的全局异常处理程序。Global Controller Advice 中的处理程序方法与基于 Controller 的异常处理程序方法相同,并且在控制器类无法处理异常时使用。

您想在一处使用异常处理策略。您可以在异常控制器中定义多个异常或使用异常生成消息。

像这样 :

@ExceptionHandler(value = { HttpClientErrorException.class, HTTPException.class, HttpMediaTypeException.class,
            HttpMediaTypeNotSupportedException.class, HttpMessageNotReadableException.class })

或者

@ExceptionHandler
@ResponseBody
ExceptionRepresentation handle(Exception exception) {
    ExceptionRepresentation body = new ExceptionRepresentation(exception.getLocalizedMessage());
    HttpStatus responseStatus = resolveAnnotatedResponseStatus(exception);

    return new ResponseEntity<ExceptionRepresentation>(body, responseStatus);
}

HttpStatus resolveAnnotatedResponseStatus(Exception exception) {
    ResponseStatus annotation = findMergedAnnotation(exception.getClass(), ResponseStatus.class);
    if (annotation != null) {
        return annotation.value();
    }

    return HttpStatus.INTERNAL_SERVER_ERROR;
}
于 2018-07-16T09:08:12.987 回答
0

这是一个解决方法。您可以捕获包装异常,然后检查异常的根本原因。这是 MySQLIntegrityConstraintViolationException 的示例,它在 spring 中由 DataIntegrityViolationException 包装:

@ExceptionHandler(DataIntegrityViolationException.class)
@ResponseBody
public ResponseEntity<Object> proccessMySQLIntegrityConstraint(DataIntegrityViolationException exception) {
    if (exception.getRootCause() instanceof MySQLIntegrityConstraintViolationException) {
       doSomething....
    } else {
        doSomethingElse...
    }
}
于 2018-07-16T13:13:04.597 回答