前言
在开发中,为了保证业务的正确性我们会对业务参数进行校验,不满足要求的参数采用throw new XxxException 来抛出异常,阻止程序继续执行,比如:用户名不可为空,密码错误等。这类异常是需要展示给用户看的,还有一类是程序抛出来的一些未知的异常,如:SQL异常,空指针异常等等,这类异常不能直接抛给用户,而是应该统一捕获后,封装成统一的错误提示返回给用户,如“系统内部异常啦”。
一、使用步骤
1.引入依赖
代码如下(示例):
<!-- 提供Servlet容器以及SpringMVC 的依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
2.开始自定义
要抛出自定义的异常。得通过继承RuntimeException自定义异常,我们需要自定义一个异常信息类
@Data // lombok相关
public class GlobalException extends RuntimeException{
/* 错误码 */
private String code;
public GlobalException(String message, String code) {
super(message);
this.code = code;
}
public GlobalException(String message) {
super(message);
}
public String getCode() {
return code;
}
}
我们自定义好异常信息类后需要编写一个异常拦截类需要用到两个关键注解,两者配合处理全局异常。
@RestControllerAdvice : 由@ControllerAdvice、@ResponseBody组成 @ExceptionHandler(xxxxx.class) :用来捕获异常,用在方法上
/** 全局异常处理器*/
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
*系统抛出的异常
*/
@ExceptionHandler(Exception.class)
public JSONResult exceptionHandler(Exception e){
e.printStackTrace();
return JSONResult.error(GlobalConstant.BASE_COMMON_SYSTEM_ERROR.getMsg(),GlobalConstant.BASE_COMMON_SYSTEM_ERROR.getCode());
}
/**
* 捕获我们自定义的异常
*/
@ExceptionHandler(GlobalException.class)
public JSONResult GlobalExceptionHandler(GlobalException e){
e.printStackTrace();
return JSONResult.error(e.getMessage(),e.getCode());
}
}
JSONResult:是我自定义的返回信息类, GlobalConstant:其他系统抛出其他错误返回信息 代码如下,需要自取:(建议抽取出公共工具包,减少代码冗余)
public class JSONResult {
private boolean success = true;
private String message = "成功";
//错误码,用来描述错误类型 ,1000 表示么有错误
private String code = "1000";
//返回的数据
private Object data;
/** 创建当前实例 **/
public static JSONResult success(){
return new JSONResult();
}
/** 创建当前实例 **/
public static JSONResult success(Object obj){
JSONResult instance = new JSONResult();
instance.setData(obj);
return instance;
}
public static JSONResult success(Object obj,String code){
JSONResult instance = new JSONResult();
instance.setCode(code);
instance.setData(obj);
return instance;
}
/** 创建当前实例 **/
public static JSONResult error(String message,String code){
JSONResult instance = new JSONResult();
instance.setMessage(message);
instance.setSuccess(false);
instance.setCode(code);
return instance;
}
public static JSONResult error(){
JSONResult jsonResult = new JSONResult();
jsonResult.setSuccess(false);
return jsonResult;
}
/** 创建当前实例 **/
public static JSONResult error(String message){
return error(message,null);
}
public enum GlobalConstant {
BASE_COMMON_SYSTEM_ERROR("系统异常,联系管理员","500");
private String msg;
private String code;
GlobalConstant(String msg,String code){
this.msg = msg;
this.code = code;
}
/* 提供方法获取*/
public String getMsg(){return msg;};
public String getCode(){ return code;};
}