Error page registrar and Global exception handling

余生长醉 提交于 2019-12-11 02:56:56

问题


I am creating a Spring Boot web application, but i am confused why people use Global Exception handlers(@ControllerAdvice) when there is Error Page Registrar which is neater and more explicit. Please can someone explain more and is it possible to call an Error page registrar from a global Exception Handler Class( class annoted with @ControllerAdvice, with an @Exceptionhandler method).


回答1:


As Brian answer, I think you can do this. I got a sample to prove this one in here if you still need to refer: https://github.com/kennytai/SampleSpringbootExceptionHandler At this sample, I use the @ControllerAdvice in class GlobalExceptionHandler to manage all exceptions from TestController.

Hope this help.




回答2:


It's actually the opposite the error pages mechanism in Spring Boot is the global one; it's catching all exceptions unhandled by the application. Note that in a Servlet environment, it's even dispatching the request back into the container on the /error path.

You're right though, this mechanism is really powerful and you can achieve a lot with it.

The other exception handling mechanisms you're mentioning are provided by Spring MVC itself. They're executed during the handling of the request and don't require an additional dispatch to the container. In some cases, they can be more limited because they offer less features than the full ErrorController (which is an MVC Controller). But unlike error pages, you can configure those to focus on only specific errors:

  • You can declare an @ExceptionHandler within a Controller and specify the type of Exception you'd like to handle
  • You can configure the @ControllerAdvice annotation to only apply to specific packages, Controllers extending a specific interface or annotated with a specific annotation

I'd say the latter are quite useful when you want to deal with business exceptions at the controller level. You can do that with error pages, but you might end up with a single error controller dealing with too many things.



来源:https://stackoverflow.com/questions/45881425/error-page-registrar-and-global-exception-handling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!