Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize unified exception handling in SpringBoot

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces how to achieve unified exception handling in SpringBoot related knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe you will have something to gain after reading this article on how to achieve unified exception handling in SpringBoot, let's take a look.

Scenario: for exception handling, our original practice is to catch exceptions at the outermost layer, such as in Controller

@ Controllerpublic class HelloController {private static final Logger logger = LoggerFactory.getLogger (HelloController.class); @ GetMapping (value = "/ hello") @ ResponseBody public Result hello () {try {/ / TODO specific logic omission. } catch (Exception e) {logger.error ("hello interface exception = {}", e); return ResultUtil.success (- 1, "system error", null);} return ResultUtil.success (0, "success", null);}}

In this way, it can also solve some of the problems, but it is impossible to get the specified exception. The introduction of global unified exception handling will greatly improve the code and reduce the generation of redundant code.

Custom exception class: note that the spring transaction will not be rolled back when a custom exception is thrown if it is inherited from RuntimeException rather than Exception and from Exception.

Public class GlobalException extends RuntimeException {private Integer code; / / because I need to return the exception information to the interface, so add code to distinguish between public GlobalException (Integer code,String message) {super (message); / / pass the custom message an exception parent class this.code = code;} public Integer getCode () {return code;} public void setCode (Integer code) {this.code = code;}}

Custom uniform exception handlers: two key annotations @ ControllerAdvice and @ ExceptionHandler

@ ControllerAdvicepublic class ExceptionHandle {@ ResponseBody / / because I need to return the thrown exception to the interface, add this note @ ExceptionHandler public Result handle (Exception e) {if (e instanceof GlobalException) {GlobalException ge = (GlobalException) e; return ResultUtil.success1 (ge.getCode (), ge.getMessage ());} return ResultUtil.success1 (- 1, "system error!");}}

Write a test class to test.

@ GetMapping (value = "/ hello1") @ ResponseBodypublic Result hello (@ RequestParam (value = "age", defaultValue = "50", required = false) Integer age) throws GlobalException {if (age)

< 10) { throw new GlobalException(ConstantEnum.LESS10.getCode(), ConstantEnum.LESS10.getMsg()); } else if (age >

50) {throw new GlobalException (ConstantEnum.MORE50.getCode (), ConstantEnum.MORE50.getMsg ());} else {return ResultUtil.success1 (0, "success");}}

Code and message are encapsulated in the ConstantEnum enumeration to facilitate unified maintenance

Public enum ConstantEnum {ERROR (- 1, "system error!"), SUCCESS (100,100, "success"), LESS10 (101, "Custom exception messages-I'm under 10"), MORE50 (5001, "Custom exception messages-I'm over 50"); private Integer code; private String msg; public Integer getCode () {return code;} public String getMsg () {return msg } ConstantEnum (Integer code, String msg) {this.code = code; this.msg = msg;}}

This is the end of the article on "how to implement unified exception handling in SpringBoot". Thank you for reading! I believe you all have a certain understanding of "how to achieve unified exception handling in SpringBoot". If you want to learn more, you are welcome to 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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report