SpringMVC之全局异常处理 ——统一返回格式(自定义异常)

向右看齐 2022-05-10 13:26 526阅读 0赞

SpringMVC之全局异常处理

老规矩开篇咱们先介绍一下背景
因当前APP越来越流行,或是提供的第三方接口等等都需要你来统一返回格式。这个时候问题就来了 ,很多时候系统的异常以及为了代码的可读性我们必然会抽出很多的间接层(例如数据格式校验、数据有效性校验等),一层层的return是否让你烦不胜烦?其实只需要抛出异常就像断言那样即可阻止程序继续执行后续业务代码。

Dennis Debruler 说过 “计算机是这样一门科学:它相信所有的问题都可以通过增加一个间接层来解决。”

首先定义好我们的返回对象

  1. package com.xxx.response.common;
  2. import java.io.Serializable;
  3. public class Response<T> implements Serializable {
  4. private static final long serialVersionUID = 1L;
  5. private Integer code;
  6. private String message;
  7. private T result;
  8. public static boolean isSuccess(Response<?> response) {
  9. return response == null ? false : ResponsCodeTypeEnum.SUCCESS.getCode().equals(response.getCode());
  10. }
  11. public Response() {
  12. this.code = ResponsCodeTypeEnum.SUCCESS.getCode();
  13. this.message = ResponsCodeTypeEnum.SUCCESS.getMessage();
  14. }
  15. public Response(Integer code, String message) {
  16. this.code = code;
  17. this.message = message;
  18. }
  19. public Response(T result) {
  20. this.code = ResponsCodeTypeEnum.SUCCESS.code;
  21. this.message = ResponsCodeTypeEnum.SUCCESS.message;
  22. this.result = result;
  23. }
  24. public Integer getCode() {
  25. return this.code;
  26. }
  27. public String getMessage() {
  28. return this.message;
  29. }
  30. public T getResult() {
  31. return this.result;
  32. }
  33. public void setCode(Integer code) {
  34. this.code = code;
  35. }
  36. public void setMessage(String message) {
  37. this.message = message;
  38. }
  39. public void setResult(T result) {
  40. this.result = result;
  41. }
  42. public String toString() {
  43. return "Response(code=" + this.getCode() + ", message=" + this.getMessage() + ", result=" + this.getResult() + ")";
  44. }
  45. //为了方便将枚举类整合至一起了可以单独建一个
  46. public enum ResponsCodeTypeEnum {
  47. SUCCESS(0, "请求成功"),
  48. SYSTEM_BUSY(100, "系统繁忙"),
  49. REQUEST_TIME_OUT(300, "请求超时"),
  50. PARAMETER_ERROR(400, "参数错误"),
  51. NETWORK_ERROR(404, "网络异常"),
  52. DATA_NOT_EXISTS(600, "数据不存在"),
  53. FAILURE(999, "未知错误");
  54. private Integer code;
  55. private String message;
  56. private ResponsCodeTypeEnum(Integer code, String message) {
  57. this.code = code;
  58. this.message = message;
  59. }
  60. public Integer getCode() {
  61. return this.code;
  62. }
  63. public String getMessage() {
  64. return this.message;
  65. }
  66. }
  67. }

接下来自定义异常

我这些写的复杂些可以去除掉你们不需要的

定义接口

  1. package com.xxx.common.exception;
  2. import java.util.Date;
  3. public interface BaseException {
  4. Integer getCode();
  5. String[] getArgs();
  6. void setTime(Date var1);
  7. Date getTime();
  8. void setClassName(String var1);
  9. String getClassName();
  10. void setMethodName(String var1);
  11. String getMethodName();
  12. void setParameters(String[] var1);
  13. String[] getParameters();
  14. void setHandled(boolean var1);
  15. boolean isHandled();
  16. String getMessage();
  17. void setI18nMessage(String var1);
  18. String getI18nMessage();
  19. }

异常工具类

  1. package com.xxx.common.exception.util;
  2. import java.io.PrintWriter;
  3. import java.io.StringWriter;
  4. public class ExceptionUtils extends org.apache.commons.lang3.exception.ExceptionUtils {
  5. public ExceptionUtils() {
  6. }
  7. public static String[] convertArgsToString(Object[] args) {
  8. String[] argsStrs = new String[args.length];
  9. for(int i = 0; i < args.length; ++i) {
  10. argsStrs[i] = String.valueOf(args[i]);
  11. }
  12. return argsStrs;
  13. }
  14. public static String toString(Throwable e) {
  15. return toString("", e);
  16. }
  17. public static String toString(String msg, Throwable e) {
  18. StringWriter w = new StringWriter();
  19. w.write(msg);
  20. PrintWriter p = new PrintWriter(w);
  21. p.println();
  22. String var4;
  23. try {
  24. e.printStackTrace(p);
  25. var4 = w.toString();
  26. } finally {
  27. p.close();
  28. }
  29. return var4;
  30. }
  31. }

超类

  1. package com.xxx.common.exception;
  2. import com.xxx.common.exception.util.ExceptionUtils;
  3. import org.springframework.core.NestedRuntimeException;
  4. import java.util.Date;
  5. public class BaseRuntimeException extends NestedRuntimeException implements BaseException {
  6. private static final long serialVersionUID = 1L;
  7. private Integer code;
  8. private Date time;
  9. private String[] args;
  10. private String className;
  11. private String methodName;
  12. private String[] parameters;
  13. private boolean handled;
  14. private String i18nMessage;
  15. public BaseRuntimeException(Integer code, String defaultMessage, Object[] args) {
  16. super(defaultMessage);
  17. this.code = code;
  18. this.args = ExceptionUtils.convertArgsToString(args);
  19. }
  20. public BaseRuntimeException(Integer code, String defaultMessage, Throwable cause, Object[] args) {
  21. super(defaultMessage, cause);
  22. this.code = code;
  23. this.args = ExceptionUtils.convertArgsToString(args);
  24. }
  25. public BaseRuntimeException(String defaultMessage, Throwable cause) {
  26. super(defaultMessage, cause);
  27. }
  28. public BaseRuntimeException(String defaultMessage) {
  29. super(defaultMessage);
  30. }
  31. public Integer getCode() {
  32. return this.code;
  33. }
  34. public Date getTime() {
  35. return this.time;
  36. }
  37. public void setTime(Date time) {
  38. this.time = time;
  39. }
  40. public String getClassName() {
  41. return this.className;
  42. }
  43. public void setClassName(String className) {
  44. this.className = className;
  45. }
  46. public String getMethodName() {
  47. return this.methodName;
  48. }
  49. public void setMethodName(String methodName) {
  50. this.methodName = methodName;
  51. }
  52. public String[] getParameters() {
  53. return this.parameters;
  54. }
  55. public void setParameters(String[] parameters) {
  56. this.parameters = parameters;
  57. }
  58. public void setHandled(boolean handled) {
  59. this.handled = handled;
  60. }
  61. public boolean isHandled() {
  62. return this.handled;
  63. }
  64. public void setI18nMessage(String i18nMessage) {
  65. this.i18nMessage = i18nMessage;
  66. }
  67. public String getI18nMessage() {
  68. return this.i18nMessage;
  69. }
  70. public String[] getArgs() {
  71. return this.args;
  72. }
  73. }

异常类

  1. package com.xxx.common.exception;
  2. public class FastRuntimeException extends BaseRuntimeException {
  3. private static final long serialVersionUID = -4954118251735823026L;
  4. public FastRuntimeException(String msg) {
  5. super(msg);
  6. }
  7. public FastRuntimeException(Integer code, String defaultMsg, Object[] args) {
  8. super(code, defaultMsg, args);
  9. }
  10. public FastRuntimeException(Integer code, String msg) {
  11. super(code, msg, new Object[0]);
  12. }
  13. public FastRuntimeException(String msg, Throwable cause) {
  14. super(msg, cause);
  15. }
  16. public FastRuntimeException(Integer code, String msg, Throwable cause) {
  17. super(code, msg, cause, new Object[0]);
  18. }
  19. public Throwable fillInStackTrace() {
  20. return this;
  21. }
  22. }

异常定义完成,可直接使用FastRuntimeException 不过我建议各个系统模块去继承FastRuntimeException 定义自己的异常

全局异常捕获

  1. package com.xxx.common.exception;
  2. import com.alibaba.dubbo.rpc.RpcException;
  3. import com.xxx.common.response.Response;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import org.springframework.validation.BindException;
  7. import org.springframework.validation.FieldError;
  8. import org.springframework.web.bind.MethodArgumentNotValidException;
  9. import org.springframework.web.bind.annotation.ControllerAdvice;
  10. import org.springframework.web.bind.annotation.ExceptionHandler;
  11. import org.springframework.web.bind.annotation.ResponseBody;
  12. import javax.validation.ValidationException;
  13. import java.util.HashMap;
  14. import java.util.Iterator;
  15. import java.util.Map;
  16. @ControllerAdvice
  17. @ResponseBody
  18. public class GlobalExceptionHandler {
  19. private Logger log = LoggerFactory.getLogger(this.getClass());
  20. public GlobalExceptionHandler() {
  21. }
  22. @ExceptionHandler({Exception.class})
  23. public Response<Map<String, String>> MethodArgumentNotValidHandler(Exception exception) throws Exception {
  24. Response<Map<String, String>> response = new Response();
  25. HashMap fieldAndMessage;
  26. Iterator var5;
  27. FieldError fieldError;
  28. if (exception instanceof MethodArgumentNotValidException) {
  29. fieldAndMessage = new HashMap();
  30. MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException)exception;
  31. var5 = methodArgumentNotValidException.getBindingResult().getFieldErrors().iterator();
  32. while(var5.hasNext()) {
  33. fieldError = (FieldError)var5.next();
  34. fieldAndMessage.put(fieldError.getField(), fieldError.getDefaultMessage());
  35. }
  36. response.setCode(Response.ResponsCodeTypeEnum.PARAMETER_ERROR.getCode());
  37. response.setMessage(Response.ResponsCodeTypeEnum.PARAMETER_ERROR.getMessage());
  38. response.setResult(fieldAndMessage);
  39. } else if (exception instanceof BindException) {
  40. fieldAndMessage = new HashMap();
  41. BindException bindException = (BindException)exception;
  42. var5 = bindException.getBindingResult().getFieldErrors().iterator();
  43. while(var5.hasNext()) {
  44. fieldError = (FieldError)var5.next();
  45. fieldAndMessage.put(fieldError.getField(), fieldError.getDefaultMessage());
  46. }
  47. response.setCode(Response.ResponsCodeTypeEnum.PARAMETER_ERROR.getCode());
  48. response.setMessage(Response.ResponsCodeTypeEnum.PARAMETER_ERROR.getMessage());
  49. response.setResult(fieldAndMessage);
  50. } else if (exception instanceof ValidationException) {
  51. response.setCode(Response.ResponsCodeTypeEnum.PARAMETER_ERROR.getCode());
  52. response.setMessage(Response.ResponsCodeTypeEnum.PARAMETER_ERROR.getMessage());
  53. } else if (exception instanceof RpcException) {
  54. response.setCode(Response.ResponsCodeTypeEnum.PARAMETER_ERROR.getCode());
  55. response.setMessage(Response.ResponsCodeTypeEnum.PARAMETER_ERROR.getMessage());
  56. } else if (exception instanceof BaseRuntimeException) {
  57. //取出我们放入异常中的code 和message 返回前端
  58. response.setCode(((BaseRuntimeException) exception).getCode());
  59. response.setMessage(exception.getMessage());
  60. }else {
  61. response.setCode(Response.ResponsCodeTypeEnum.FAILURE.getCode());
  62. response.setMessage(Response.ResponsCodeTypeEnum.FAILURE.getMessage());
  63. }
  64. this.log.error(exception.getMessage(), exception);
  65. return response;
  66. }
  67. }

打完收工,一切的代码都是可以不做任何修改直接拿去使用的。大大的方便了我们的业务开发。接下来请让你的校验工作变成间接层吧。

我的简化版登录校验工厂
在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,526人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java全局异常处理-定义异常处理

    > 哈喽!大家好,我是旷世奇才李先生 > 文章持续更新,可以微信搜索【小奇JAVA面试】第一时间阅读,回复【资料】更有我为大家准备的福利哟,回复【项目】获取我为大家准备的项