In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article is about how to understand SpringBoot exception handling, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.
Brief introduction of SpringBoot exception handling
I'll write the repetition function. In SpringBoot projects, there are global exception handling and return wrapper, etc. The front end of the return is accompanied by succ, code, msg, data and other fields. It is easy to solve in the case of a single project. When there are many micro-service modules, in many cases, developers copy the original code to build another project, resulting in the upgrade of these functions need to modify multiple services. On this basis, we encapsulate a component unified-dispose-springboot-starter that contains some basic exception handling and return wrapper functions.
Rely on add startup function
Add dependent ps: please use the latest version of the actual version version
Com.purgeteam unified-dispose-springboot-starter 0.1.1.RELEASE
Add @ EnableGlobalDispose annotation to the startup class to enable the following functions.
@ EnableGlobalDispose@SpringBootApplicationpublic class GlobalDisposeSpringBootApplication {public static void main (String [] args) {SpringApplication.run (GlobalDisposeSpringBootApplication.class, args);}} One exception handling ⚠️
System exceptions often occur in projects, such as NullPointerException and so on. If the error is not handled by default, springboot will respond to the default error prompt, which is not friendly to the user experience, the system level error, and the user cannot perceive it. Even if the error is 500, you can give the user a friendly prompt similar to server desertion.
The module also contains some basic exception handling methods (and there is no need to write any code to already have basic exception handling), as well as some common exception code, users only need to care about business exception handling, and can be thrown directly through throw new exceptions.
Exception handling includes type # generic 500exception Exception class catch 500exception handling # Feign exception FeignException class capture ClientException class capture # business custom BusinessException class capture business generic custom exception # parameter check exception HttpMessageNotReadableException parameter error exception BindException parameter error exception program actively throws exception throw new BusinessException (BusinessErrorCode.BUSINESS_ERROR); / / or throw new BusinessException ("CLOUD800", "no extra inventory")
Generally speaking, it is not recommended to throw a general BusinessException exception directly. You should add the corresponding domain exception handling class and the corresponding enumeration error type to the corresponding module.
Such as member module: create UserException exception class, UserErrorCode enumeration, and UserExceptionHandler unified intercept class.
UserException:
@ Datapublic class UserException extends RuntimeException {private String code; private boolean isShowMsg = true; / * use enumeration to pass parameters * * @ param errorCode exception enumeration * / public UserException (UserErrorCode errorCode) {super (errorCode.getMessage ()); this.setCode (errorCode.getCode ());}}
UserErrorCode:
@ Getterpublic enum UserErrorCode {/ * permission exception * / NOT_PERMISSIONS ("CLOUD401", "you do not have operation permission"),; private String code; private String message; CommonErrorCode (String code, String message) {this.code = code; this.message = message;}}
UserExceptionHandler:
@ Slf4j@RestControllerAdvicepublic class UserExceptionHandler {/ * UserException class capture * / @ ExceptionHandler (value = UserException.class) public Result handler (UserException e) {log.error (e.getMessage (), e); return Result.ofFail (e.getCode (), e.getMessage ());}}
The final business usage is as follows:
/ / determine whether you have permission to throw an exception throw new UserException (UserErrorCode.NOT_PERMISSIONS)
In the above way, an exception is thrown and will be handled by the module. The front desk returns as follows:
{"succ": false, / / successful "ts": 1566467628851, / / timestamp "data": null, / / data "code": "CLOUD800", / / error type "msg": "business exception", / / error description "fail": true} Tow unified return seal?
In REST-style development, avoid usually telling the foreground whether the return was successful or not, as well as the status code. Here we usually do the wrapper processing of util when we return, such as Result-like class, which contains succ, code, msg, data and other fields.
The API call processing is similar to the following:
@ GetMapping ("hello") public Result list () {return Result.ofSuccess ("hello");}
Results:
{"succ": ture, / / successful "ts": 1566467628851, / / timestamp "data": "hello", / / data "code": null, / / error type "msg": null, / / error description "fail": true} function use
By default, all web controller are encapsulated in the following return format.
Interface:
@ GetMapping ("test") public String test () {return "test";}
Return
{"succ": true, / / successful "ts": 1566386951005, / / timestamp "data": "test", / / data "code": null, / / error type "msg": null, / / error description "fail": false} ignore encapsulation Note: @ IgnorReponseAdvice
The allowed scope of @ IgnorReponseAdvice is: class + method, which indicates that the return of a method under this class will ignore the return wrapper.
Interface:
@ IgnorReponseAdvice / / ignore data wrappers can be added to classes and methods @ GetMapping ("test") public String test () {return "test";}
Return to test
There are many repeated code in the project, which we can simplify in a certain way in order to achieve a certain purpose and reduce the amount of development. PurgeTeam has some excellent open source components to reduce the amount of daily development.
The above is how to understand SpringBoot exception handling, the editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.
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.