全局异常整合
整合环境springboot2.3
创建异常类
public class GlobalException extends Exception{
private CodeMsg codeMsg;
// CodeMsg是一个存储异常信息类 没有的话使用字符串即可
public GlobalException(CodeMsg codeMsg) {
super(codeMsg.toString());
this.codeMsg = codeMsg;
}
public GlobalException(String msg) {
super(msg);
CodeMsg error = new CodeMsg(1, "error");
error.setMsg(msg);
this.codeMsg = error;
}
public CodeMsg getCodeMsg() {
return codeMsg;
}
}
全局异常处理
import com.qs.heipa.utils.AjaxResult;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.*;
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
@ExceptionHandler(value = Exception.class)
public Object exceptionHandler(Exception e) {
e.printStackTrace();
if (e instanceof GlobalException) {
GlobalException ex = (GlobalException) e;
return AjaxResult.fail(ex.getCodeMsg());
} else if (e instanceof BindException) {
//请求参数异常捕捉
BindException ex = (BindException) e;
List<ObjectError> errors = ex.getAllErrors();
String msg = "";
for (ObjectError obj : errors) {
msg += obj.getDefaultMessage();
}
return AjaxResult.fail(CodeMsg.BIND_ERROR.fillArgs(msg));
} else if (e instanceof HttpRequestMethodNotSupportedException) {
//请求方式错误捕捉
return AjaxResult.fail(CodeMsg.REQUEST_TYPE_FAIL);
} else if (e instanceof MissingServletRequestParameterException) {
//请求参数异常捕捉
CodeMsg codeMsg = new CodeMsg(603, "缺少请求参数");
codeMsg.setMsg("缺少请求参数:" + e.getMessage());
return AjaxResult.fail(codeMsg);
} else if (e instanceof MethodArgumentTypeMismatchException) {
CodeMsg codeMsg = new CodeMsg(602, "请求参数错误");
codeMsg.setMsg("请求参数错误:" + e.getMessage());
return AjaxResult.fail(codeMsg);
}else if (e instanceof ConstraintViolationException) {
//断言异常捕捉
ConstraintViolationException ex = (ConstraintViolationException) e;
Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations();
Iterator<ConstraintViolation<?>> iterator = constraintViolations.iterator();
StringBuilder msg = new StringBuilder();
while (iterator.hasNext()) {
ConstraintViolation<?> cvl = iterator.next();
msg.append(cvl.getMessageTemplate());
msg.append("、");
}
msg.deleteCharAt(msg.length() - 1);
return AjaxResult.fail(new CodeMsg(602, msg.toString()));
}
else {
//其他异常统一报错
return AjaxResult.fail(CodeMsg.SERVER_ERROR);
}
}
}