springboot自定义业务异常

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":"自定义错误"}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容