In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
Today, I will talk to you about how to handle and analyze Spring Boot unified exceptions. Many people may not know much about it. In order to make you understand better, the editor has summarized the following contents for you. I hope you can get something according to this article.
Talk about abnormality
"want to cross the Yellow River ice and snow blocked this big river, will climb Taihang snow all over the sky", no matter life or the computer world will inevitably have anomalies, the last article RESTful API returned a unified JSON data format to explain the unified return processing, this is to request that everything is normal This article will explain how to deal with exceptions in a unified way, as well as the implementation principle behind it. The old routines are implemented first, and then explain the principle. With the foundation of the previous article, I believe that I will be familiar with this article.
Implement a new business exception
The new BusinessException.class class represents a business exception. Note that this is a Runtime exception.
@ Data@AllArgsConstructorpublic final class BusinessException extends RuntimeException {private String errorCode; private String errorMsg;} add uniform exception handling static method
Add the static method errorResult to the CommonResult class to receive exception codes and exception messages:
Public static CommonResult errorResult (String errorCode, String errorMsg) {CommonResult commonResult = new CommonResult (); commonResult.errorCode = errorCode; commonResult.errorMsg = errorMsg; commonResult.status =-1; return commonResult;} configuration
Also use the @ RestControllerAdvice annotation to add a unified exception to the configuration:
RestControllerAdvice ("com.example.unifiedreturn.api") static class UnifiedExceptionHandler {@ ExceptionHandler (BusinessException.class) public CommonResult handleBusinessException (BusinessException be) {return CommonResult.errorResult (be.getErrorCode (), be.getErrorMsg ());}}
The three parts are done. Here, no matter in Controller or Service, as long as BusinessException is thrown, we will return to the front end a unified data format.
test
Modify the method in UserController to throw an exception directly:
@ GetMapping ("/ {id}") public UserVo getUserById (@ PathVariable Long id) {throw new BusinessException ("1001", "query user exception by ID");}
Enter: http://localhost:8080/users/1 in browser
Throw an exception in Service:
@ Servicepublic class UserServiceImpl implements UserService {/ * query user * * @ param id * @ return * / @ Override public UserVo getUserById (Long id) {throw new BusinessException ("1001", "query user exception based on ID");}}
Run to get the same result, so let's throw an exception as much as possible (it's photographable as a programmer).
The realization process of anatomy
The process of dissection is quite complicated. In order to better say (yin) wei (wo) wo (lan), I would like to say the most important thing. I really hope that the children's shoes in this article will go to the crime scene to find clues or instantiate HandlerExceptionResolver Bean in the WebMvcConfigurationSupport category.
@ Beanpublic HandlerExceptionResolver handlerExceptionResolver () {List exceptionResolvers = new ArrayList (); configureHandlerExceptionResolvers (exceptionResolvers); if (exceptionResolvers.isEmpty ()) {addDefaultHandlerExceptionResolvers (exceptionResolvers);} extendHandlerExceptionResolvers (exceptionResolvers); HandlerExceptionResolverComposite composite = new HandlerExceptionResolverComposite (); composite.setOrder (0); composite.setExceptionResolvers (exceptionResolvers); return composite;}
In the same way as in the previous article, ExceptionHandlerExceptionResolver implements the InitializingBean interface and rewrites the afterPropertiesSet method:
@ Overridepublic void afterPropertiesSet () {/ / Do this first, it may add ResponseBodyAdvice beans initExceptionHandlerAdviceCache ();...} private void initExceptionHandlerAdviceCache () {if (getApplicationContext () = = null) {return;} List adviceBeans = ControllerAdviceBean.findAnnotatedBeans (getApplicationContext ()); AnnotationAwareOrderComparator.sort (adviceBeans); for (ControllerAdviceBean adviceBean: adviceBeans) {Class beanType = adviceBean.getBeanType () If (beanType = = null) {throw new IllegalStateException ("Unresolvable type for ControllerAdviceBean:" + adviceBean);} / / focus on this construction method ExceptionHandlerMethodResolver resolver = new ExceptionHandlerMethodResolver (beanType); if (resolver.hasExceptionMappings ()) {this.exceptionHandlerAdviceCache.put (adviceBean, resolver) } if (ResponseBodyAdvice.class.isAssignableFrom (beanType)) {this.responseBodyAdvice.add (adviceBean);}
Let's focus on the construction method I marked with comments above. The code is easy to understand. Take a closer look. In fact, it is to filter out the method marked with @ ExceptionHandler annotation and put it into the collection for subsequent global exception capture matching.
/ * * A constructor that finds {@ link ExceptionHandler} methods in the given type. * @ param handlerType the type to introspect * / public ExceptionHandlerMethodResolver (Class handlerType) {for (Method method: MethodIntrospector.selectMethods (handlerType, EXCEPTION_HANDLER_METHODS)) {for (Class paramType: method.getParameterTypes ()) {if (Throwable.class.isAssignableFrom (paramType)) {result.add ((Class)
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.