1. GlobalExceptionHandler
package com.vipsoft.web.boot.exception;
import com.vipsoft.web.boot.utils.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.List;
/**
* 全局异常处理器
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 处理自定义异常
*/
@ExceptionHandler(CustomException.class)
public Result handleException(CustomException e) {
// 打印异常信息
logger.error("### 异常信息:{} ###", e.getMessage());
return new Result(e.getCode(), e.getMessage());
}
/**
* 参数错误异常
*/
@ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
public Result handleException(Exception e) {
if (e instanceof MethodArgumentNotValidException) {
MethodArgumentNotValidException validException = (MethodArgumentNotValidException) e;
BindingResult result = validException.getBindingResult();
StringBuffer errorMsg = new StringBuffer();
if (result.hasErrors()) {
List<ObjectError> errors = result.getAllErrors();
errors.forEach(p -> {
FieldError fieldError = (FieldError) p;
errorMsg.append(fieldError.getDefaultMessage()).append(",");
logger.error("### 请求参数错误:{" + fieldError.getObjectName() + "},field{" + fieldError.getField() + "},errorMessage{" + fieldError.getDefaultMessage() + "}");
});
}
} else if (e instanceof BindException) {
BindException bindException = (BindException) e;
if (bindException.hasErrors()) {
logger.error("### 请求参数错误: {}", bindException.getAllErrors());
}
}
return new Result(10001, "参数无效");
}
/**
* 处理所有不可知的异常
*/
@ExceptionHandler(Exception.class)
public Result handleOtherException(Exception e) {
//打印异常堆栈信息
e.printStackTrace();
// 打印异常信息
logger.error("### 不可知的异常:{} ###", e.getMessage());
return new Result(40001, "系统内部错误");
}
}
2.CustomException
package com.vipsoft.web.boot.exception;
public class CustomException extends RuntimeException {
private static final long serialVersionUID = 1L;
private int code;
private String msg;
public CustomException(String msg) {
super(msg);
this.code = 500;
this.msg = msg;
}
public CustomException(String msg, Throwable e) {
super(msg, e);
this.msg = msg;
}
public CustomException(int code, String msg) {
super(msg);
this.code = code;
this.msg = msg;
}
public CustomException(int code, String msg, Throwable e) {
super(msg, e);
this.code = code;
this.msg = msg;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
可以结合:DevOps 运维提醒 钉钉群通知,做些预警通知