美文网首页
springboot自定义业务异常

springboot自定义业务异常

作者: 青青子衿zq | 来源:发表于2021-01-02 18:07 被阅读0次

1.自定义异常类需要继承Exception(异常)类,这里继承RuntimeException类

public class BusinessExceptionextends RuntimeException {

private Integercode;

    public BusinessException(int code,String message){

super(message);

        this.code=code;

    }

public IntegergetCode() {

return code;

    }

public void setCode(Integer code) {

this.code = code;

    }

}

2.自定义全局捕获异常

@RestControllerAdvice

public class ExceptionHanddler {

@ExceptionHandler(BusinessException.class)

public Mapbus(BusinessException e){

HashMap map =new HashMap<>();

        map.put("code",e.getCode());

        map.put("message",e.getMessage());

        return map;

    }

}

3.测试自定义异常类

@RequestMapping("/error")

public Stringerror(int i){

if (i==1){

throw new BusinessException(600,"自定义错误");

    }

return "success";

}

4.测试

浏览器请求:http://localhost:8080/yinhang/error?i=1

响应 {"code":600,"message":"自定义错误"}

相关文章

网友评论

      本文标题:springboot自定义业务异常

      本文链接:https://www.haomeiwen.com/subject/bafpoktx.html