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