1.新建GlobalExceptionHandler 全局异常处理类
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
@ExceptionHandler(MyException.class)
public ReturnJson<Object> myExceptionHandler(MyException ex) {
return new ReturnJson<Object>(ResultStatusEnum.FAILURE.getCode(), ResultStatusEnum.FAILURE.getMessage(), null);
}
@ExceptionHandler(RuntimeException.class)
public ReturnJson<Object> runtimeExceptionHandler(RuntimeException ex) {
return new ReturnJson<Object>(ResultStatusEnum.FAILURE.getCode(), ResultStatusEnum.FAILURE.getMessage(), null);
}
}
2.自定义异常类MyException继承RuntimeException
@Getter
public class MyException extends RuntimeException{
private int code;
private String message;
public MyException(int code, String message) {
this.code = code;
this.message = message;
}
public MyException(ResultStatusEnum resultStatusEnum) {
this.code = resultStatusEnum.getCode();
this.message = resultStatusEnum.getMessage();
}
}
3.用到的其他类
@Data
public class ReturnJson<T> {
private int code;
private String message;
private T info;
public ReturnJson(int code,String message ,T info) {
this.code=code;
this.message=message;
this.info=info;
}
}
@NoArgsConstructor
@AllArgsConstructor
public enum ResultStatusEnum {
SUCCESS(200, "请求成功!"),
FAILURE(400, "请求失败!");
@Getter
@Setter
private int code;
@Getter
@Setter
private String message;
}