Home > Java > javaTutorial > How to implement unified exception handling in SpringBoot

How to implement unified exception handling in SpringBoot

WBOY
Release: 2023-05-10 22:01:04
forward
1183 people have browsed it

Scenario: For exception handling, our original approach is to generally capture the exception in the outermost layer. For example, in the Controller

@Controller
public class HelloController {
 
  private static final Logger logger = LoggerFactory.getLogger(HelloController.class);
 
  @GetMapping(value = "/hello")
  @ResponseBody
  public Result hello() {
    try {
      //TODO 具体的逻辑省略……
    } catch (Exception e) {
      logger.error("hello接口异常={}", e);
      return ResultUtil.success(-1, "system error", null);
    }
    return ResultUtil.success(0, "success", null);
  }
}
Copy after login

This can also solve some problems, but it cannot be obtained. Introducing global unified exception handling for self-specified exceptions will greatly improve the code and reduce the generation of redundant code.

Custom exception class: Note that it must inherit from RuntimeException instead of Exception. If it inherits from Exception, the spring transaction will not roll back when a custom exception is thrown.

public class GlobalException extends RuntimeException {
 
  private Integer code; //因为我需要将异常信息也返回给接口中,所以添加code区分
 
  public GlobalException(Integer code,String message) {
    super(message);  //把自定义的message传递个异常父类
    this.code = code;
  }
 
  public Integer getCode() {
    return code;
  }
 
  public void setCode(Integer code) {
    this.code = code;
  }
}
Copy after login

Customization Unified exception handler: the two more critical annotations @ControllerAdvice and @ExceptionHandler

@ControllerAdvice
public class ExceptionHandle {
 
  @ResponseBody  //因为我需要将抛出的异常返回给接口,所以加上此注解
  @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!");
  }
 
}
Copy after login

Write a test class to test

@GetMapping(value = "/hello1")
@ResponseBody
public Result hello(@RequestParam(value = "age", defaultValue = "50", required = false) Integer age) throws GlobalException {
  if (age  50) {
    throw new GlobalException(ConstantEnum.MORE50.getCode(), ConstantEnum.MORE50.getMsg());
  } else {
    return ResultUtil.success1(0, "success");
  }
}
Copy after login

Encapsulate the code and message in ConstantEnum In the enumeration, it is convenient for unified maintenance

public enum ConstantEnum {
 
  ERROR(-1, "system error!"),
  SUCCESS(100, "success"),
  LESS10(101, "自定义异常信息-我小于10岁"),
  MORE50(5001, "自定义异常信息-我大于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;
  }
}
Copy after login

How to implement unified exception handling in SpringBoot

The above is the detailed content of How to implement unified exception handling in SpringBoot. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template