feat:增加controller层的异常处理

This commit is contained in:
石崇礼 2025-01-15 17:17:27 +08:00
parent b0bd972e66
commit 7b0a2a98cd
5 changed files with 302 additions and 0 deletions

View File

@ -0,0 +1,141 @@
package com.dpkj.common.exception;
import com.dpkj.common.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* controller控制器异常处理接口实现类
* <p>其它module可以集成此类进行controller层的异常处理</p>
* @author <a href="https://gitee.com/shi-chongli">石头人</a>
*/
@Slf4j
@Component
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
public class ControllerAdvice {
/**
* controller方法中的参数校验失败但是前提是要使用
* #@Validated注解开启参数校验
*
* @param e 异常
* @return Result
*/
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public Result<String> bindingException(MethodArgumentNotValidException e) {
// 获得所有校验出错的返回集
BindingResult bindingResult = e.getBindingResult();
List<FieldError> fieldErrors = bindingResult.getFieldErrors();
// 循环获得所有校验异常的字段
Map<String, String> fieldMap = new HashMap<>();
for (FieldError fieldError : fieldErrors) {
fieldMap.put(fieldError.getField(), fieldError.getDefaultMessage());
}
String errMsg = fieldMap.values().toString().replaceAll("]", "").replaceAll("\\[", "");
log.warn(errMsg);
// 返回给前端
return Result.error(errMsg);
}
/**
* 处理空指针异常
* @param nullPointerException 空指针异常
* @return Result
*/
@ExceptionHandler(value = java.lang.NullPointerException.class)
public Result<String> nullPointException(java.lang.NullPointerException nullPointerException) {
log.error("空指针异常类型: {},信息: {}", nullPointerException.getClass(),nullPointerException.getMessage());
return Result.error(ErrorEnum.NULL_POINTER_EXCEPTION);
}
/**
* 所有的运行时异常抛出异常
* @param throwable 异常
* @return Result
*/
@ExceptionHandler(value = Throwable.class)
public Result<String> handleException(Throwable throwable) {
log.error("异常类型: {}, {}, 信息为: {}", throwable.getCause(), throwable.getClass(), throwable.getMessage());
if (throwable instanceof RRException){
RRException rrException = (RRException) throwable;
return Result.error(rrException.getCode(), rrException.getMsg());
}
return Result.error(ErrorEnum.RUNTIME_EXCEPTION);
}
/**
* http信息无可读
* @param e 异常
* @return Result
*/
@ExceptionHandler(value = HttpMessageNotReadableException.class)
public Result<String> httpMessageNotReadAbleException(HttpMessageNotReadableException e){
log.warn("异常类型: {} 无可读信息: {}", e.getClass(), e.getMessage());
return Result.error(ErrorEnum.HTTP_MESSAGE_NOT_READABLE_EXCEPTION);
}
/**
* 运行时异常
* @param e 运行异常对象
* @return Result
*/
@ExceptionHandler(value = RuntimeException.class)
public Result<String> runtimeException(RuntimeException e){
if (!e.getMessage().isEmpty()){
log.error("运行时异常 消息为: {}", e.getMessage());
}
if (e instanceof RRException){
RRException rrException = (RRException) e;
return Result.error(rrException.getCode(), rrException.getMsg());
}
return Result.error(ErrorEnum.RUNTIME_EXCEPTION);
}
/**
* 请求不支持
* @return Result
*/
@ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
public Result<String> httpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e){
log.warn("暂不支持该请求: {}", e.getMessage());
return Result.error("暂不支持此请求方式");
}
/**
* 参数类型错误
* @return Result
*/
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public Result<String> methodArgument(MethodArgumentTypeMismatchException e){
log.warn("参数发生错误: {}", e.getMessage());
return Result.error("参数发生错误");
}
/**
* 缺少请求参数
* @param e 缺少请求参数异常
* @return Result
*/
@ExceptionHandler(MissingServletRequestParameterException.class)
public Result<String> exception(MissingServletRequestParameterException e){
log.warn("缺少请求参数: {}", e.getMessage());
return Result.error("缺少请求参数");
}
}

View File

@ -0,0 +1,70 @@
package com.dpkj.common.exception;
import lombok.Getter;
/**
* 错误返回枚举类
*/
@Getter
public enum ErrorEnum implements ErrorInterface{
// ==========================================================================
/**
* 成功范围
* @code 200
* @apiNote 访问成功
*/
SUCCESS(200, "访问成功"),
/**
* 系统异常
* @code 500
* @apiNote 系统异常
*/
FAIL(500, "系统异常"),
/**
* 所有的空指针异常
* @code 10002
* @apiNote 填写信息为空
*/
NULL_POINTER_EXCEPTION(501, "填写信息为空"),
/**
* 运行时异常,
* @code 10003
* @apiNote 系统发生错误请联系管理员
*/
RUNTIME_EXCEPTION(502, "系统发生错误,请联系管理员"),
/**
* Http传入的参数没有可以读的数据
* @code 10004
* @apiNote 传入的数据不可读
*/
HTTP_MESSAGE_NOT_READABLE_EXCEPTION(503, "传入的数据不可读"),
// ==========================================================================
;
private final Integer code;
private final String message;
ErrorEnum(Integer code, String message){
this.message = message;
this.code = code;
}
@Override
public int getCode(){
return this.code;
}
@Override
public String getMessage(){
return this.message;
}
}

View File

@ -0,0 +1,23 @@
package com.dpkj.common.exception;
/**
* 错误枚举接口所有的错误枚举都需要实现该接口,如果需要自定义
* 错误信息可通过实现该接口与RespBean进行使用
*
* @author <a href="https://gitee.com/shi-chongli">石头人</a>
* @see com.dpkj.common.vo.Result
* @since 2023-07-27 13:05:00
*/
public interface ErrorInterface {
/**
* 获取响应码
*/
int getCode();
/**
* 获取响应信息
*/
String getMessage();
}

View File

@ -0,0 +1,59 @@
package com.dpkj.common.exception;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 总的异常所有的自定义异常都需要继承类
*
* @author <a href="https://gitee.com/shi-chongli">石头人</a>
* @since 2023-07-24 09:42:00
*/
@EqualsAndHashCode(callSuper = true)
@Data
public class RRException extends RuntimeException{
private static final long serialVersionUID = 1L;
private String msg;
private int code = 500;
public RRException(){
super("系统错误");
this.msg = "系统错误";
}
public RRException(Throwable throwable){
super(throwable);
}
public RRException(String msg) {
super(msg);
this.msg = msg;
}
public RRException(String msg, Throwable e) {
super(msg, e);
this.msg = msg;
}
public RRException(int code, String msg) {
super(msg);
this.msg = msg;
this.code = code;
}
public RRException(ErrorInterface error){
super(error.getMessage());
this.code = error.getCode();
this.msg = error.getMessage();
}
public RRException(int code,String msg, Throwable e) {
super(msg, e);
this.msg = msg;
this.code = code;
}
}

View File

@ -1,6 +1,7 @@
package com.dpkj.common.vo; package com.dpkj.common.vo;
import com.dpkj.common.constant.CommonConst; import com.dpkj.common.constant.CommonConst;
import com.dpkj.common.exception.ErrorEnum;
import lombok.Data; import lombok.Data;
import java.io.Serializable; import java.io.Serializable;
@ -69,6 +70,14 @@ public class Result<T> implements Serializable {
return error(CommonConst.SC_500, msg, null); return error(CommonConst.SC_500, msg, null);
} }
public static <T> Result<T> error(ErrorEnum errorEnum) {
return error(errorEnum.getCode(), errorEnum.getMessage(), null);
}
public static <T> Result<T> error(int code, String message) {
return error(code, message, null);
}
public static <T> Result<T> error(int code, String msg, T data) { public static <T> Result<T> error(int code, String msg, T data) {
Result<T> r = new Result<T>(); Result<T> r = new Result<T>();
r.setCode(code); r.setCode(code);