在项目里面加入统一的返回信息和异常处理
新建 文件如下
public interface BaseErrorInfoInterface { /** * 错误码 */ String getResultCode(); /** * 错误描述 */ String getResultMsg(); }
public enum CommonEnum implements BaseErrorInfoInterface { // 数据操作错误定义 BODY_NOT_MATCH("400", "请求的数据格式不符!"), SIGNATURE_NOT_MATCH("401", "请求的数字签名不匹配!"), NOT_FOUND("404", "未找到该资源!"), INTERNAL_SERVER_ERROR("500", "服务器内部错误!"), SERVER_BUSY("503", "服务器正忙,请稍后再试!"); /** * 错误码 */ private String resultCode; /** * 错误描述 */ private String resultMsg; CommonEnum(String resultCode, String resultMsg) { this.resultCode = resultCode; this.resultMsg = resultMsg; } @Override public String getResultCode() { return resultCode; } @Override public String getResultMsg() { return resultMsg; } }
public class BizException extends RuntimeException{ private static final long serialVersionUID = 1L; /** * 错误码 */ protected String errorCode; /** * 错误信息 */ protected String errorMsg; public BizException() { super(); } public BizException(BaseErrorInfoInterface errorInfoInterface) { super(errorInfoInterface.getResultCode()); this.errorCode = errorInfoInterface.getResultCode(); this.errorMsg = errorInfoInterface.getResultMsg(); } public BizException(BaseErrorInfoInterface errorInfoInterface, Throwable cause) { super(errorInfoInterface.getResultCode(), cause); this.errorCode = errorInfoInterface.getResultCode(); this.errorMsg = errorInfoInterface.getResultMsg(); } public BizException(String errorMsg) { super(errorMsg); this.errorMsg = errorMsg; } public BizException(String errorCode, String errorMsg) { super(errorCode); this.errorCode = errorCode; this.errorMsg = errorMsg; } public BizException(String errorCode, String errorMsg, Throwable cause) { super(errorCode, cause); this.errorCode = errorCode; this.errorMsg = errorMsg; } public String getErrorCode() { return errorCode; } public void setErrorCode(String errorCode) { this.errorCode = errorCode; } public String getErrorMsg() { return errorMsg; } public void setErrorMsg(String errorMsg) { this.errorMsg = errorMsg; } public String getMessage() { return errorMsg; } @Override public Throwable fillInStackTrace() { return this; } }
@ControllerAdvice public class GlobalExceptionHandler { private Logger logger = LoggerFactory.getLogger(this.getClass()); /** * 处理自定义的业务异常 * * @param req * @param e * @return */ @ExceptionHandler(value = BizException.class) @ResponseBody public BasicResult bizExceptionHandler(HttpServletRequest req, BizException e) { logger.error("发生业务异常e:{}", e.getMessage()); return BasicResult.fail(e.getErrorCode(), e.getErrorMsg()); } /** * 处理空指针的异常 * * @param req * @param e * @return */ @ExceptionHandler(value = NullPointerException.class) @ResponseBody public BasicResult exceptionHandler(HttpServletRequest req, NullPointerException e) { logger.error("发生空指针异常e:{}", e.getMessage()); return BasicResult.fail(e.getMessage()); } /** * 处理其他异常 * * @param req * @param e * @return */ @ExceptionHandler(value = Exception.class) @ResponseBody public BasicResult exceptionHandler(HttpServletRequest req, Exception e) { logger.error("未知异常e:{}", e.getMessage()); return BasicResult.fail(e.getMessage()); } /** * 处理所有接口数据验证异常 * * @param e * @return */ @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseBody public BasicResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { logger.error("数据绑定异常e:{}", e.getMessage()); return BasicResult.fail(e.getMessage()); } /** * 请求类型异常 * * @param e * @return */ @ExceptionHandler(HttpRequestMethodNotSupportedException.class) @ResponseBody public BasicResult httpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) { logger.error("请求类型异常e:{}", e.getMessage()); return BasicResult.fail(e.getMessage()); } /** * 数据绑定异常 * * @param e * @return */ @ExceptionHandler(MissingServletRequestParameterException.class) @ResponseBody public BasicResult missingServletRequestParameterException(MissingServletRequestParameterException e) { logger.error("数据绑定异常e:{}", e.getMessage()); return BasicResult.fail(CommonEnum.BODY_NOT_MATCH.getResultMsg()); } }
public class BasicResult<T> { private T data; private Long total; public Boolean success; /** * 返回状态码 */ private String code; /** * 返回消息 */ private String message; /** * 异常堆栈 */ private String fullStackTrace; private final static String SUCCESS_CODE = "0"; private final static String DEFAULT_FAIL_CODE = "-1"; public Boolean getSuccess() { return success; } public void setSuccess(Boolean success) { this.success = success; } public boolean isSuccess() { return Objects.equals(BasicResult.SUCCESS_CODE, this.code); } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getFullStackTrace() { return fullStackTrace; } public void setFullStackTrace(String fullStackTrace) { this.fullStackTrace = fullStackTrace; } public T getData() { return data; } public void setData(T data) { this.data = data; } public Long getTotal() { return total; } public void setTotal(Long total) { this.total = total; } /** * 成功 * * @return */ public static BasicResult success() { BasicResult basicResult = new BasicResult(); basicResult.setCode(SUCCESS_CODE); return basicResult; } /** * 成功 * * @param data * @param <T> * @return */ public static <T> BasicResult<T> success(T data) { BasicResult<T> basicResult = new BasicResult<>(); basicResult.setCode(SUCCESS_CODE); basicResult.setData(data); return basicResult; } /** * 成功 * * @param data * @param message * @param <T> * @return */ public static <T> BasicResult<T> success(T data, String message) { BasicResult<T> basicResult = new BasicResult<>(); basicResult.setCode(SUCCESS_CODE); basicResult.setMessage(message); basicResult.setData(data); return basicResult; } /** * 成功 * * @param data * @param <T> * @return */ public static <T> BasicResult<T> success(T data, long total) { BasicResult<T> basicResult = new BasicResult<>(); basicResult.setCode(SUCCESS_CODE); basicResult.setData(data); basicResult.setTotal(total); return basicResult; } /** * 成功 * * @param data * @param message * @param <T> * @return */ public static <T> BasicResult<T> success(T data, String message, Boolean success) { BasicResult<T> basicResult = new BasicResult<>(); basicResult.setCode(SUCCESS_CODE); basicResult.setMessage(message); basicResult.setData(data); basicResult.setSuccess(success); return basicResult; } /** * 成功 * * @param data * @param total * @param <T> * @return */ public static <T> BasicResult<T> success(T data, Long total) { BasicResult<T> basicResult = new BasicResult<>(); basicResult.setCode(SUCCESS_CODE); basicResult.setData(data); basicResult.setTotal(total); return basicResult; } /** * 失败 * * @param code * @param <T> * @return */ static <T> BasicResult<T> fail(String code, Throwable throwable) { BasicResult<T> basicResult = new BasicResult<>(); basicResult.setCode(code); basicResult.setMessage(throwable.getMessage()); basicResult.setFullStackTrace(JSON.toJSONString(throwable)); return basicResult; } /** * 失败 * * @param code * @param <T> * @return */ public static <T> BasicResult<T> fail(String code, String message) { BasicResult<T> basicResult = new BasicResult<>(); basicResult.setCode(code); basicResult.setMessage(message); return basicResult; } /** * 失败 * * @param message * @param <T> * @return */ public static <T> BasicResult<T> fail(String message) { BasicResult<T> basicResult = new BasicResult<>(); basicResult.setCode(DEFAULT_FAIL_CODE); basicResult.setMessage(message); return basicResult; } /** * 失败 * * @param throwable * @param <T> * @return */ static <T> BasicResult<T> fail(Throwable throwable, Boolean isFull) { BasicResult<T> basicResult = new BasicResult<>(); basicResult.setCode("500"); basicResult.setMessage("系统出错啦"); if (isFull) { basicResult.setFullStackTrace(JSON.toJSONString(throwable)); } else { basicResult.setFullStackTrace(throwable.getMessage()); } return basicResult; } }
其中需要对UserAction类进行改造,让我们去访问的时候会被对应的异常捕获
@RestController @RequestMapping("/user") public class UserAction { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Value("${server.port}") String port; @Resource private UserMapper userMapper; @PostMapping("/hi") public BasicResult<String> hi(@RequestParam String name) { logger.info("----- selectAll method test ------"); List<User> userList = userMapper.selectList(null); logger.info("userList:{}", JSON.toJSON(userList)); return BasicResult.success("hi " + name + ",i am from port:" + port); } @GetMapping("/getUser") public BasicResult<String> getUser(@RequestParam Integer name) { logger.info("----- selectAll method test ------"); List<User> userList = userMapper.selectList(null); logger.info("userList:{}", JSON.toJSON(userList)); return BasicResult.success("hi " + name + ",i am from port:" + port); } }
BasicResult 是包装的统一返回信息。
GlobalExceptionHandler是程序异常的时候对异常的捕获,然后返回对应的错误信息。
BizException是自定义的系统异常。
启动项目,浏览器访问http://127.0.0.1:10001/user/hi
控制台输出如图
异常会在HttpRequestMethodNotSupportedException进行处理,然后返回给用户设置的统一的数据格式。
返回格式如下