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":"自定義錯誤"}