@ControllerAdvice超过@ExceptionHandler或HandlerExceptionResolver处理异常有哪些优点? [英] What are the advantages of @ControllerAdvice over @ExceptionHandler or HandlerExceptionResolver for handling exceptions?
问题描述
Spring 3.2 介绍了在Spring MVC应用程序中处理异常的 @ControllerAdvice
注释。但在此版本之前,Spring在Spring MVC应用程序中处理异常,其中有 @ExceptionHandler
或 HandlerExceptionResolver
。那么为什么 Spring 3.2 引入了 @ControllerAdvice
注释来处理异常?我坚信 Spring 3.2 引入了 @ControllerAdvice
注释 以解决 @ExceptionHandler
或 HandlerExceptionResolver
或使 异常处理更强大 。
Spring 3.2 introduced @ControllerAdvice
annotation for handling exceptions in a Spring MVC application. But prior to this version Spring had @ExceptionHandler
or HandlerExceptionResolver
to handling exceptions in a Spring MVC application. Then why Spring 3.2 introduced @ControllerAdvice
annotation for handling exceptions? I strongly believe that Spring 3.2 introduced @ControllerAdvice
annotation to address the limitations of @ExceptionHandler
or HandlerExceptionResolver
or make the exceptions handling more stronger.
任何人都可以解释 @ControllerAdvice
超过 @ExceptionHandler
或 HandlerExceptionResolver
用于处理异常?
Can any one explain the advantages of @ControllerAdvice
over @ExceptionHandler
or HandlerExceptionResolver
for handling exceptions?
推荐答案
@ExceptionHandler
@ExceptionHandler
在控制器级别下工作,只对该<
@ExceptionHandler
@ExceptionHandler
works at the Controller level and it is only active for that particular Controller, not globally for the entire application.
这将解决应用程序抛出的任何异常。它用于将标准的Spring异常解析为其对应的HTTP状态代码。它无法控制响应的正文,这意味着它不会响应的主体设置任何内容。它不会映射响应的状态代码,而是正文为空。
This will resolve any exception thrown by the application. It is used to resolve standard Spring exceptions to their corresponding HTTP Status Codes. It does not have control over the body of the response, means it does not set anything to the body of the Response.It does map the status code on the response but the body is null.
@ControllerAdvice
用于Spring MVC应用程序中的全局错误处理。它还具有对响应正文和状态代码的完全控制。
@ControllerAdvice
used for global error handling in the Spring MVC application.It also has full control over the body of the response and the status code.
这篇关于@ControllerAdvice超过@ExceptionHandler或HandlerExceptionResolver处理异常有哪些优点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!