English 中文(简体)
多种语文
原标题:Setting Precedence of Multiple @ControllerAdvice @ExceptionHandlers

我有多个附加说明的班级,有<代码>@ControllerAdvice,每个班有@ExceptionHandler方法。

One handles Exception with the intention that if no more specific handler is found, this should be used.

令人痛心的是,MVC似乎总是使用最通用的案件(Exception),而不是更具体的案件(例如IOException)。

难道这怎么会期望春天会发生吗? I m试图效仿泽西岛的模式,该模式评估每一条<条码>外观Mapper(等值部分),以确定其所申报的类型在多大程度上与所投出的例外情况无关,并且始终使用最近的祖先。

最佳回答

人们是否希望春天会这样做?

至春天4.3.7时,这里使用的是:HandlerceptExceptionResolver<<<<>>>a>,处理手递解方法提出的例外情况。

通过缺席,MVC组合登记了单一<>代码>HandlerExceptionResolver bean, a rel=“noreferer”HandlerExceptionResolverComitepos<

出席其他<代码>HandlerExceptionResolvers的代表。

其他决心者

  1. ExceptionHandlerExceptionResolver
  2. ResponseStatusExceptionResolver
  3. DefaultHandlerExceptionResolver

registered in that order. For the purpose of this question we only care about ExceptionHandlerExceptionResolver.

An AbstractHandlerMethodExceptionResolver that resolves exceptions through @ExceptionHandler methods.

在背景初始阶段,春季将产生一个<>rel=“noreferer”>ControllerAdviceBean>>>>>>,每个ExceptionHandlerExceptionResolver> 将从背景中检索这些内容,并用 rel=“诺referer”AnnotationAwareOrderCompartor<<<<>a> ......

is an extension of OrderComparator that supports Spring s Ordered interface as well as the @Order and @Priority annotations, with an order value provided by an Ordered instance overriding a statically defined annotation value (if any).

然后登记 例(可用@ExceptionHandler方法计算,其唯一处理类型除外)。 这两条最后按以下顺序添加:LinkedHashMap(保存顺序)。

当出现例外情况时,<代码>ExceptionHandlerExceptionResolver将通过这些<代码>ExceptionHandlerMethodResolver加以推广,并使用第一个可以处理例外情况的代码。

因此,以下一点是:如果您有@ControllerAdvice with an @ExceptionHandler, 可在另一个上登记的@ControllerAdvice , 附有@ExceptionHandler的更具体例外情形,如ExceptionHandler, , 第一个例外情形将获得确认。 rel=“noreferer”>。

问题回答

Sotirios Delimanolis在他的答复中非常有帮助,关于进一步调查,我们发现,在春季,3.2.4条路途上,“The Code for @ControllerAdvice note”也检查了“Order Note”的存在,并对主计长AdviceBeans名单进行了分类。

The resulting default order for all controllers without the @Order annotation is Ordered#LOWEST_PRECEDENCE which means if you have one controller that needs to be the lowest priority then ALL your controllers need to have a higher order.

这里的一个例子是,在用户档案接收或实时接收发生时,如何与主计长Advice和命令说明一起开设两个例外的手递班,以便作出适当反应。

class UserProfileException extends RuntimeException {
}

@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
class UserProfileExceptionHandler {
    @ExceptionHandler(UserProfileException)
    @ResponseBody
    ResponseEntity<ErrorResponse> handleUserProfileException() {
        ....
    }
}

@ControllerAdvice
@Order(Ordered.LOWEST_PRECEDENCE)
class DefaultExceptionHandler {

    @ExceptionHandler(RuntimeException)
    @ResponseBody
    ResponseEntity<ErrorResponse> handleRuntimeException() {
        ....
    }
}
  • See ControllerAdviceBean#initOrderFromBeanType()
  • See ControllerAdviceBean#findAnnotatedBeans()
  • See ExceptionHandlerExceptionResolver#initExceptionHandlerAdviceCache()

欢乐!

你们也可以使用一些价值,如以下。

@Order(value = 100)

Lower values have higher priority. The default value is * {@code Ordered.LOWEST_PRECEDENCE},indicating lowest priority (losing to any other * specified order value)

重要类别:

@Order(Ordered.HIGHEST_PRECEDENCE)
public class FunctionalResponseEntityExceptionHandler 
{
    private final Logger logger = LoggerFactory.getLogger(FunctionalResponseEntityExceptionHandler.class);

    @ExceptionHandler(EntityNotFoundException.class)
    public final ResponseEntity<Object> handleFunctionalExceptions(EntityNotFoundException ex, WebRequest request)
    {
        logger.error(ex.getMessage() + " " + ex);
        ExceptionResponse exceptionResponse= new ExceptionResponse(new Date(), ex.getMessage(),
                request.getDescription(false),HttpStatus.NOT_FOUND.toString());
        return new ResponseEntity<>(exceptionResponse, HttpStatus.NOT_FOUND);
    }
}

Other Exceptions with Low priority

@ControllerAdvice
public class GlobalResponseEntityExceptionHandler extends ResponseEntityExceptionHandler
{
    private final Logger logger = LoggerFactory.getLogger(GlobalResponseEntityExceptionHandler.class);
    
    @ExceptionHandler(Exception.class)
    public final ResponseEntity<Object> handleAllException(Exception ex, WebRequest request)
    {
        logger.error(ex.getMessage()+ " " + ex);
        ExceptionResponse exceptionResponse= new ExceptionResponse(new Date(), ex.toString(),
                request.getDescription(false),HttpStatus.INTERNAL_SERVER_ERROR.toString());
    }
}

There s a similar situation convered in the excellent "Exception Handling in Spring MVC" post on the Spring blog, in the section entitled Global Exception Handling. Their scenario involves checking for ResponseStatus annotations registered on the exception class, and if present, rethrowing the exception to let the framework handle them. You might be able to use this general tactic - try to determine if there is a might be a more appropriate handler out there and rethrowing.

或者,还有其他一些例外处理战略,可以由你来研究。

如果你想要分离你的例外情况处理员(如我),你可以使用<代码>@Import来做到这一点。

@ControllerAdvice
class MyCustomExceptionHandler {
  ...
}
@ControllerAdvice
class MyOtherCustomExceptionHandler {
  ...
}
@Import({MyCustomExceptionHandler.class,MyOtherCustomExceptionHandler.class})
@ControllerAdvice
@Order(Ordered.LOWEST_PRECEDENCE)
class ApplicationExceptionHandler{
  //Generic exception handlers
}




相关问题
handling exceptions IN Action Filters

Is there a better way to handle exceptions that occur inside an Action Filter itself in ASP .NET MVC? There re 2 ways I can think of at the moment. Using a try catch and setting the HTTP Status ...

既可捕获,又可举出例外。

我有一种办法,可以进入亚洲开发银行,因此,我国的亚行在多瑙河航道中的所有 st子都位于一个试捕区。 它正在追捕Kexception

Cross compiler exception handling - Can it be done safely?

I am doing some maintenance on a C++ windows dll library that is required to work with different VC++ compilers (as I don’t want to address different mangling schemes). I have already eliminated any ...

File Handling Issue

I am developing a tool in c#, at one instance I start writing into a xml file continuously using my tool,when i suddenly restart my machine the particular xml file gets corrupted, what is the reason ...

Watch a memory location/install data breakpoint from code?

We have a memory overwrite problem. At some point, during the course of our program, a memory location is being overwritten and causing our program to crash. the problem happens only in release mode. ...

Unit Test for Exceptions Message

Is there a simple (Attribute-driven) way to have the following test fail on the message of the exception. [TestMethod()] [ExpectedException(typeof(ArgumentException))] public void ExceptionTestTest() ...

热门标签