legs+ 发表于 2023-5-24 14:35:44

spring boot自定义异常:

控制器

@RestController
public class TestController {
    @RequestMapping("/BusinessException")
    public String testResponseStatusExceptionResolver(@RequestParam("i") int i){
      if (i==0){
            throw new BusinessException(600,"自定义业务错误");
      }
            return "success";
    }

}
实体类
public class BusinessException extends RuntimeException{
    //自定义错误码
    private Integer code;
    //自定义构造器,必须输入错误码及内容
    public BusinessException(int code,String msg) {
      super(msg);
      this.code = code;
    }

    public Integer getCode() {
      return code;
    }

    public void setCode(Integer code) {
      this.code = code;
    }
}
自定义业务处理业务异常类
@ControllerAdvice
public class CustomerBusinessExceptionHandler {
    @ResponseBody
    @ExceptionHandler(BusinessException.class)
    public Map<String, Object> businessExceptionHandler(BusinessException e) {
      Map<String, Object> map = new HashMap<String, Object>();
      map.put("code", e.getCode());
      map.put("message", e.getMessage());
      //发生异常进行日志记录,此处省略
      return map;
    }
}

页: [1]
查看完整版本: spring boot自定义异常: