请选择 进入手机版 | 继续访问电脑版

spring boot自定义异常:

legs+之专栏 legs+之专栏 813 人阅读 | 0 人回复 | 2023-05-24

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
控制器

  1. @RestController
  2. public class TestController {
  3.     @RequestMapping("/BusinessException")
  4.     public String testResponseStatusExceptionResolver(@RequestParam("i") int i){
  5.         if (i==0){
  6.             throw new BusinessException(600,"自定义业务错误");
  7.         }
  8.               return "success";
  9.     }

  10. }
复制代码
实体类
  1. public class BusinessException extends RuntimeException{
  2.     //自定义错误码
  3.     private Integer code;
  4.     //自定义构造器,必须输入错误码及内容
  5.     public BusinessException(int code,String msg) {
  6.         super(msg);
  7.         this.code = code;
  8.     }

  9.     public Integer getCode() {
  10.         return code;
  11.     }

  12.     public void setCode(Integer code) {
  13.         this.code = code;
  14.     }
  15. }
复制代码
自定义业务处理业务异常类
  1. @ControllerAdvice
  2. public class CustomerBusinessExceptionHandler {
  3.     @ResponseBody
  4.     @ExceptionHandler(BusinessException.class)
  5.     public Map<String, Object> businessExceptionHandler(BusinessException e) {
  6.         Map<String, Object> map = new HashMap<String, Object>();
  7.         map.put("code", e.getCode());
  8.         map.put("message", e.getMessage());
  9.         //发生异常进行日志记录,此处省略
  10.         return map;
  11.     }
  12. }
复制代码


您需要登录后才可以回帖 登录 | 立即注册

本版积分规则