一.编写一个全局异常类
public class GlobalException extends RuntimeException{
/**
* 错误对象
* @param message
*/
public GlobalException(String message){
super(message);
}
}
二.编写全局异常处理类
/**
* 全局异常处理
*/
//@ControllerAdvice
@RestControllerAdvice
public class GlobalExceptionHandler {
//拦截异常 : 这个注解就可以拦截器 GlobalException 异常
@ExceptionHandler(GlobalException.class)
public JSONResult globalException(GlobalException e){
e.printStackTrace();
return JSONResult.error(e.getMessage());
}
//拦截器其他异常
@ExceptionHandler(Exception.class)
public JSONResult exception(Exception e){
e.printStackTrace();
return JSONResult.error(ErrorCode.SYSTEM_ERROR.getMessage(),ErrorCode.SYSTEM_ERROR.getCode());
}
}
这里使用的是web项目的注解需要导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
三.为了扩展性更好编写枚举类保存错误码
/** 系统错误码 **/
public enum ErrorCode {
SYSTEM_ERROR("500","系统内部异常");
//错误码
private String code;
//错误信息
private String message;
ErrorCode(String code, String message) {
this.code = code;
this.message = message;
}
public String getCode() {
return code;
}
public String getMessage() {
return message+"["+code+"]";
}
}