尧图网站设计 尧图网站设计YAOTU DESIGN
ARTICLE DETAIL

资讯详情

深耕网站设计与一线实操的经验洞察。

全局异常捕获,自定义异常处理类和返回体封装

全局异常捕获,自定义异常处理类和返回体封装 文件结构ExceptionCode.Java 自定义异常码注解package com.example.xxxxx.config.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; Retention(RetentionPolicy.RUNTIME) Target({ElementType.FIELD}) // 表明该注解只能放在类的字段上 public interface ExceptionCode { // 响应码code int value() default 10000; // 响应信息msg String message() default 参数校验错误; }SystemExceptionType.java 系统异常类型枚举package com.example.xxxxxx.config.enums; import com.example.xxxxx.config.exception.ServiceExceptionDefinition; public class SystemExceptionType { public static final ServiceExceptionDefinition SUCCESS new ServiceExceptionDefinition(true, 200, 操作成功); public static final ServiceExceptionDefinition SAVE_SUCCESS new ServiceExceptionDefinition(true, 200, 保存成功); public static final ServiceExceptionDefinition UPDATE_SUCCESS new ServiceExceptionDefinition(true, 200, 编辑成功); public static final ServiceExceptionDefinition DELETE_SUCCESS new ServiceExceptionDefinition(true, 200, 删除成功); public static final ServiceExceptionDefinition ERROR new ServiceExceptionDefinition(false, 9999, 操作异常); public static final ServiceExceptionDefinition SAVE_ERROR new ServiceExceptionDefinition(false, 9999, 保存异常); public static final ServiceExceptionDefinition UPDATE_ERROR new ServiceExceptionDefinition(false, 9999, 编辑异常); public static final ServiceExceptionDefinition DELETE_ERROR new ServiceExceptionDefinition(false, 9999, 删除异常); public static final ServiceExceptionDefinition PARAM_ERROR new ServiceExceptionDefinition(false, 10002, 参数错误); public static final ServiceExceptionDefinition REQUEST_PARAMETER_LACK new ServiceExceptionDefinition(false, 10016, 缺少请求参数); public static final ServiceExceptionDefinition REQUEST_PARAMETER_ANALYSIS new ServiceExceptionDefinition(false, 10017, 参数解析失败); public static final ServiceExceptionDefinition REQUEST_PARAMETER_BIND new ServiceExceptionDefinition(false, 10018, 参数绑定失败); public static final ServiceExceptionDefinition METHOD_NOT_ALLOWED new ServiceExceptionDefinition(false, 10019, 不支持当前请求方法); public static final ServiceExceptionDefinition HTTP_CLIENT_ERROR new ServiceExceptionDefinition(false, 10020, 不支持当前媒体类型); public static final ServiceExceptionDefinition NULL_POINT new ServiceExceptionDefinition(false, 10022, 空指针异常); public static final ServiceExceptionDefinition MISSING_PATH_VARIABLE new ServiceExceptionDefinition(false, 10024, 未检测到路径参数); public static final ServiceExceptionDefinition MISSING_HEAD_VARIABLE new ServiceExceptionDefinition(false, 10026, 未检测到请求头参数); public static final ServiceExceptionDefinition TYPE_MISMATCH new ServiceExceptionDefinition(false, 10025, 参数类型匹配失败); public static final ServiceExceptionDefinition FILE_SIZE_BIG_ERR new ServiceExceptionDefinition(false, 10026, 文件不能超过10M); public static final ServiceExceptionDefinition EXCEL_EXPORT_ERROR new ServiceExceptionDefinition(false, 10101, 导出Excel失败请联系网站管理员); public static final ServiceExceptionDefinition DELETE_ID_NOT_EXIST new ServiceExceptionDefinition(false, 11001, 删除ID不能为空); public static final ServiceExceptionDefinition TOKEN_EXCEPTION new ServiceExceptionDefinition(false, 10086, TOKEN异常); public static final ServiceExceptionDefinition TOKEN_NOT_EXIST new ServiceExceptionDefinition(false, 10085, 缺少TOKEN); public static final ServiceExceptionDefinition TENANTID_EXCEPTION new ServiceExceptionDefinition(false, 10186, 租户异常); public static final ServiceExceptionDefinition TENANTID_NOT_EXIST new ServiceExceptionDefinition(false, 10185, 缺少租户); public static final ServiceExceptionDefinition DEFECT_SYSTEM_CLASSES_CONFIG new ServiceExceptionDefinition(false, 10021, 系统配置缺少值班班次配置); }GlobalExceptionHandler.java 全局异常处理器package com.example.xxxxx.config.exception; import com.example.xxxxx.config.annotation.ExceptionCode; import com.example.xxxxx.config.enums.SystemExceptionType; import com.example.xxxxx.config.vo.R; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.TypeMismatchException; import org.springframework.http.HttpStatus; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.util.StringUtils; import org.springframework.validation.BindException; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.HttpMediaTypeNotSupportedException; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.MissingPathVariableException; import org.springframework.web.bind.MissingRequestHeaderException; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.multipart.MaxUploadSizeExceededException; import org.springframework.web.servlet.NoHandlerFoundException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.lang.reflect.Field; Slf4j RestControllerAdvice public class GlobalExceptionHandler { ExceptionHandler(MethodArgumentNotValidException.class) public R MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) throws NoSuchFieldException { // 从异常对象中拿到错误信息 String defaultMessage e.getBindingResult().getAllErrors().get(0).getDefaultMessage(); // 参数的Class对象等下好通过字段名称获取Field对象 Class? parameterType e.getParameter().getParameterType(); // 拿到错误的字段名称 String fieldName e.getBindingResult().getFieldError().getField(); Field field parameterType.getDeclaredField(fieldName); // 获取Field对象上的自定义注解 ExceptionCode annotation field.getAnnotation(ExceptionCode.class); // 有注解的话就返回注解的响应信息 if (annotation ! null) { return R.error().code(annotation.value()).message(StringUtils.isEmpty(annotation.message()) ? defaultMessage : annotation.message()); } // 没有注解就提取错误提示信息进行返回统一错误码 return R.error().code(SystemExceptionType.PARAM_ERROR.getCode()).message(defaultMessage); } /** * 400 - Bad Request */ ResponseStatus(HttpStatus.BAD_REQUEST) ExceptionHandler(MissingServletRequestParameterException.class) public R handleMissingServletRequestParameterException(MissingServletRequestParameterException e) { log.error(缺少请求参数, e); return R.error().code(SystemExceptionType.REQUEST_PARAMETER_LACK.getCode()) .message(SystemExceptionType.REQUEST_PARAMETER_LACK.getMsg()); } /** * 400 - Bad Request */ ResponseStatus(HttpStatus.BAD_REQUEST) ExceptionHandler(MaxUploadSizeExceededException.class) public R SizeLimitExceededException(HttpServletRequest request, HttpServletResponse response, MaxUploadSizeExceededException e) { log.error(文件上传过大,e); return R.error().code(SystemExceptionType.FILE_SIZE_BIG_ERR.getCode()) .message(SystemExceptionType.FILE_SIZE_BIG_ERR.getMsg()); } /** * 400 - Bad Request */ ResponseStatus(HttpStatus.BAD_REQUEST) ExceptionHandler(HttpMessageNotReadableException.class) public R handleHttpMessageNotReadableException(HttpMessageNotReadableException e) { log.error(参数解析失败, e); return R.error().code(SystemExceptionType.REQUEST_PARAMETER_ANALYSIS.getCode()) .message(SystemExceptionType.REQUEST_PARAMETER_ANALYSIS.getMsg()); } /** * 400 - Bad Request */ ResponseStatus(HttpStatus.BAD_REQUEST) ExceptionHandler(TypeMismatchException.class) public R handleHttpMessageNotReadableException(TypeMismatchException e) { log.error(参数类型匹配失败, e); return R.error().code(SystemExceptionType.TYPE_MISMATCH.getCode()) .message(SystemExceptionType.TYPE_MISMATCH.getMsg()); } /** * 400 - Bad Request */ ResponseStatus(HttpStatus.BAD_REQUEST) ExceptionHandler(BindException.class) public R handleBindException(BindException e) { log.error(参数绑定失败, e); BindingResult result e.getBindingResult(); FieldError error result.getFieldError(); String field error.getField(); String code error.getDefaultMessage(); String message String.format(%s:%s, field, code); return R.error().code(SystemExceptionType.REQUEST_PARAMETER_BIND.getCode()) .message(message); } /** * 404 - Bad Request */ ResponseStatus(HttpStatus.NOT_FOUND) ExceptionHandler(NoHandlerFoundException.class) public R handleBindException(NoHandlerFoundException e) { log.error(查找有没有对应的控制器404, e); return R.error().code(SystemExceptionType.REQUEST_PARAMETER_BIND.getCode()) .message(SystemExceptionType.REQUEST_PARAMETER_BIND.getMsg()); } /** * 405 - Method Not Allowed */ ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED) ExceptionHandler(HttpRequestMethodNotSupportedException.class) public R handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) { log.error(不支持当前请求方法, e); return R.error().code(SystemExceptionType.METHOD_NOT_ALLOWED.getCode()) .message(SystemExceptionType.METHOD_NOT_ALLOWED.getMsg()); } /** * 415 - Unsupported Media Type */ ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE) ExceptionHandler(MissingPathVariableException.class) public R handleHttpMediaTypeNotSupportedException(MissingPathVariableException e) { log.error(请求路径缺少参数, e); return R.error().code(SystemExceptionType.MISSING_PATH_VARIABLE.getCode()) .message(SystemExceptionType.MISSING_PATH_VARIABLE.getMsg()); } /** * 415 - Unsupported Media Type */ ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE) ExceptionHandler(MissingRequestHeaderException.class) public R handleHttpHeadException(MissingRequestHeaderException e) { log.error(请求头缺少参数, e); return R.error().code(SystemExceptionType.MISSING_HEAD_VARIABLE.getCode()) .message(SystemExceptionType.MISSING_HEAD_VARIABLE.getMsg()); } /** * 415 - Unsupported Media Type */ ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE) ExceptionHandler(HttpMediaTypeNotSupportedException.class) public R handleHttpMediaTypeNotSupportedException(Exception e) { log.error(不支持当前媒体类型, e); return R.error().code(SystemExceptionType.HTTP_CLIENT_ERROR.getCode()) .message(SystemExceptionType.HTTP_CLIENT_ERROR.getMsg()); } /** * -------- 通用异常处理方法 -------- **/ ExceptionHandler(Exception.class) public R error(Exception e) { log.error(未捕捉异常, e); e.printStackTrace(); return R.error().code(500).message(e.getMessage()); // 通用异常结果 } /** * -------- 指定异常处理方法 -------- **/ ExceptionHandler(NullPointerException.class) public R error(NullPointerException e) { e.printStackTrace(); log.error(e.getMessage(),e); return R.setData(SystemExceptionType.NULL_POINT); } ExceptionHandler(HttpClientErrorException.class) public R error(IndexOutOfBoundsException e) { e.printStackTrace(); log.error(e.getMessage(),e); return R.setData(SystemExceptionType.HTTP_CLIENT_ERROR); } /** * -------- 自定义定异常处理方法 -------- **/ ExceptionHandler(ServiceException.class) public R error(ServiceException e) { log.error(e.getMessage(),e); if (e.getMessage().contains(SystemExceptionType.TOKEN_EXCEPTION.getMsg())) { log.error(e.getMessage()); } else { e.getStackTrace(); } return R.error().message(e.getMessage()).code(e.getCode()); } }ServiceException.java 自定义业务异常类package com.example.xxxxx.config.exception; import java.io.Serializable; public class ServiceException extends RuntimeException implements Serializable { private int code; public int getCode() { return code; } public void setCode(int code) { this.code code; } public ServiceException() { } public ServiceException(String message, int code) { super(message); this.code code; } public ServiceException(ServiceExceptionDefinition definition) { super(definition.getMsg()); this.code definition.getCode(); } }ServiceExceptionDefinition.java 异常定义类package com.example.xxxxx.config.exception; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; Data NoArgsConstructor AllArgsConstructor public class ServiceExceptionDefinition { private boolean success; private int code; private String msg; }MsgResult.java 响应格式(未用)package com.example.xxxxx.config.vo; import lombok.Data; Data public class MsgResult { public MsgResult(int _code, String _result, String _msg, Object _data){ this.msg _msg; this.code _code; this.result _result; this.data _data; } /** * 返回状态码301警告0成功500错误 */ private int code; /** * 返回结果success成功error失败 */ private String result; /** * 返回消息 */ private String msg; /** * 返回内容 */ private Object data; }P.java 分页结果封装类package com.example.xxxxx.config.vo; import lombok.Data; import java.io.Serializable; import java.util.ArrayList; import java.util.List; Data public class PT implements Serializable { /** * 总数量 */ private Long total; /** * 数据 */ private ListT rows; public P() { } public P(ListT list, Long total) { this.rows list; this.total total; } public P(Long total) { this.rows new ArrayList(); this.total total; } public static T PT empty() { return new P(0L); } public static T PT empty(Long total) { return new P(total); } }R.java统一响应结果封装类package com.example.xxxxx.config.vo; import com.example.xxxxx.config.enums.SystemExceptionType; import com.example.xxxxx.config.exception.ServiceExceptionDefinition; import lombok.Data; Data public class RT { /** * 成功 */ private Boolean success; /** * 状态码 */ private Integer code; /** * 信息 */ private String message; // /** // * 结果 // */ // private MapString, Object result new HashMap(); /** * 结果 */ private T result; // 构造器私有 private R() { } // 通用返回成功 public static R ok() { R r new R(); r.setSuccess(true); r.setCode(SystemExceptionType.SUCCESS.getCode()); r.setMessage(SystemExceptionType.SUCCESS.getMsg()); return r; } // 通用返回成功 public static R okSave() { R r new R(); r.setSuccess(true); r.setCode(SystemExceptionType.SAVE_SUCCESS.getCode()); r.setMessage(SystemExceptionType.SAVE_SUCCESS.getMsg()); return r; } // 通用返回成功 public static R okUpdate() { R r new R(); r.setSuccess(true); r.setCode(SystemExceptionType.UPDATE_SUCCESS.getCode()); r.setMessage(SystemExceptionType.UPDATE_SUCCESS.getMsg()); return r; } // 通用返回成功 public static R okDelete() { R r new R(); r.setSuccess(true); r.setCode(SystemExceptionType.DELETE_SUCCESS.getCode()); r.setMessage(SystemExceptionType.DELETE_SUCCESS.getMsg()); return r; } // 通用返回失败未知错误 public static R error() { R r new R(); r.setSuccess(false); r.setCode(SystemExceptionType.ERROR.getCode()); r.setMessage(SystemExceptionType.ERROR.getMsg()); return r; } public static R errorSave() { R r new R(); r.setSuccess(false); r.setCode(SystemExceptionType.SAVE_ERROR.getCode()); r.setMessage(SystemExceptionType.SAVE_ERROR.getMsg()); return r; } public static R errorUpdate() { R r new R(); r.setSuccess(false); r.setCode(SystemExceptionType.UPDATE_ERROR.getCode()); r.setMessage(SystemExceptionType.UPDATE_ERROR.getMsg()); return r; } public static R errorDelete() { R r new R(); r.setSuccess(false); r.setCode(SystemExceptionType.DELETE_ERROR.getCode()); r.setMessage(SystemExceptionType.DELETE_ERROR.getMsg()); return r; } // 设置结果形参为结果枚举 public static R setData(ServiceExceptionDefinition result) { R r new R(); r.setSuccess(result.isSuccess()); r.setCode(result.getCode()); r.setMessage(result.getMsg()); return r; } /** * ------------使用链式编程返回类本身----------- **/ // 自定义返回数据 public R result(T model) { this.setResult(model); return this; } // // 自定义返回数据 // public R result(MapString, Object map) { // this.setResult(map); // return this; // } // // // 通用设置data // public R result(String key, Object value) { // this.result.put(key, value); // return this; // } // 自定义状态信息 public R message(String message) { this.setMessage(message); return this; } // 自定义状态码 public R code(Integer code) { this.setCode(code); return this; } // 自定义返回结果 public R success(Boolean success) { this.setSuccess(success); return this; } }结果示例
返回列表