1. 实现思路

通过RestControllerAdvice 实现全局异常处理

@RestControllerAdvice主要有3个功能:

  1. 捕获全局异常: 能够捕获controller 中抛出的制定类型的异常,从而进行指定的处理
  2. 进行数据绑定
  3. 全局数据预处理

2. 创建返回格式及异常类

2.1 创建异常处理接口

  1. /**
  2. * @author ml
  3. */
  4. public interface BaseErrorInfoInterface {
  5. /**
  6. * 获取错误码
  7. * @return 错误码
  8. */
  9. String getResultCode();
  10. /**
  11. * 获取错误信息
  12. * @return 错误信息
  13. */
  14. String getResultMsg();
  15. }

2.2 创建自定义异常类

  1. /**
  2. * 自定义异常类
  3. * @author ml
  4. */
  5. public class BizException extends RuntimeException{
  6. private static final long serialVersionUID = 1350751357838080111L;
  7. /**
  8. * 错误码
  9. */
  10. protected String errorCode;
  11. /**
  12. * 错误信息
  13. */
  14. protected String errorMsg;
  15. public BizException() {
  16. super();
  17. }
  18. public BizException(BaseErrorInfoInterface errorInfoInterface) {
  19. super(errorInfoInterface.getResultCode());
  20. this.errorCode = errorInfoInterface.getResultCode();
  21. this.errorMsg = errorInfoInterface.getResultMsg();
  22. }
  23. public BizException(BaseErrorInfoInterface errorInfoInterface, Throwable cause) {
  24. super(errorInfoInterface.getResultCode(), cause);
  25. this.errorCode = errorInfoInterface.getResultCode();
  26. this.errorMsg = errorInfoInterface.getResultMsg();
  27. }
  28. public BizException(String errorMsg) {
  29. super(errorMsg);
  30. this.errorMsg = errorMsg;
  31. }
  32. public BizException(String errorCode, String errorMsg) {
  33. super(errorCode);
  34. this.errorCode = errorCode;
  35. this.errorMsg = errorMsg;
  36. }
  37. public BizException(String errorCode, String errorMsg, Throwable cause) {
  38. super(errorCode, cause);
  39. this.errorCode = errorCode;
  40. this.errorMsg = errorMsg;
  41. }
  42. public String getErrorCode() {
  43. return errorCode;
  44. }
  45. public void setErrorCode(String errorCode) {
  46. this.errorCode = errorCode;
  47. }
  48. public String getErrorMsg() {
  49. return errorMsg;
  50. }
  51. public void setErrorMsg(String errorMsg) {
  52. this.errorMsg = errorMsg;
  53. }
  54. @Override
  55. public Throwable fillInStackTrace() {
  56. return this;
  57. }
  58. }

2.3 创建自定义异常枚举

  1. /**
  2. * 自定义异常枚举
  3. * @author ml
  4. */
  5. public enum ExceptionEnum implements BaseErrorInfoInterface {
  6. // 数据操作错误定义
  7. SUCCESS("2000", "成功!"),
  8. BODY_NOT_MATCH("4000", "请求的数据格式不符!"),
  9. INTERNAL_SERVER_ERROR("5000", "服务器内部错误!"),
  10. SERVER_BUSY("5003", "服务器正忙,请稍后再试!");
  11. private final String resultCode;
  12. private final String resultMsg;
  13. ExceptionEnum(String resultCode, String resultMsg) {
  14. this.resultCode = resultCode;
  15. this.resultMsg = resultMsg;
  16. }
  17. @Override
  18. public String getResultCode() {
  19. return this.resultCode;
  20. }
  21. @Override
  22. public String getResultMsg() {
  23. return this.resultMsg;
  24. }
  25. }

2.4 自定义数据返回结构

  1. /**
  2. * 自定义数据返回结构
  3. *
  4. * @author ml
  5. */
  6. public class ResultResponse {
  7. /**
  8. * 响应代码
  9. */
  10. private String code;
  11. /**
  12. * 响应消息
  13. */
  14. private String message;
  15. /**
  16. * 响应结果
  17. */
  18. private Object result;
  19. public ResultResponse() {
  20. }
  21. public ResultResponse(BaseErrorInfoInterface errorInfo) {
  22. this.code = errorInfo.getResultCode();
  23. this.message = errorInfo.getResultMsg();
  24. }
  25. /**
  26. * 成功
  27. */
  28. public static ResultResponse success() {
  29. return success(null);
  30. }
  31. /**
  32. * 成功
  33. */
  34. public static ResultResponse success(Object data) {
  35. ResultResponse rb = new ResultResponse();
  36. rb.setCode(ExceptionEnum.SUCCESS.getResultCode());
  37. rb.setMessage(ExceptionEnum.SUCCESS.getResultMsg());
  38. rb.setResult(data);
  39. return rb;
  40. }
  41. /**
  42. * 失败
  43. */
  44. public static ResultResponse error(BaseErrorInfoInterface errorInfo) {
  45. ResultResponse rb = new ResultResponse();
  46. rb.setCode(errorInfo.getResultCode());
  47. rb.setMessage(errorInfo.getResultMsg());
  48. rb.setResult(null);
  49. return rb;
  50. }
  51. /**
  52. * 失败
  53. */
  54. public static ResultResponse error(BizException errorInfo) {
  55. ResultResponse rb = new ResultResponse();
  56. rb.setCode(errorInfo.getErrorCode());
  57. rb.setMessage(errorInfo.getErrorMsg());
  58. rb.setResult(null);
  59. return rb;
  60. }
  61. /**
  62. * 失败
  63. */
  64. public static ResultResponse error(String code, String message) {
  65. ResultResponse rb = new ResultResponse();
  66. rb.setCode(code);
  67. rb.setMessage(message);
  68. rb.setResult(null);
  69. return rb;
  70. }
  71. /**
  72. * 失败
  73. */
  74. public static ResultResponse error(String message) {
  75. ResultResponse rb = new ResultResponse();
  76. rb.setCode("-1");
  77. rb.setMessage(message);
  78. rb.setResult(null);
  79. return rb;
  80. }
  81. @Override
  82. public String toString() {
  83. return JSONObject.toJSONString(this);
  84. }
  85. public String getCode() {
  86. return code;
  87. }
  88. public void setCode(String code) {
  89. this.code = code;
  90. }
  91. public String getMessage() {
  92. return message;
  93. }
  94. public void setMessage(String message) {
  95. this.message = message;
  96. }
  97. public Object getResult() {
  98. return result;
  99. }
  100. public void setResult(Object result) {
  101. this.result = result;
  102. }
  103. }

3. 创建全局异常处理类

  1. /**
  2. * 全局异常处理
  3. * @author ml
  4. */
  5. @RestControllerAdvice
  6. public class GlobalExceptionHandler {
  7. private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
  8. /**
  9. * 自定义异常
  10. * @param req request
  11. * @param e exception
  12. */
  13. @ExceptionHandler(value = BizException.class)
  14. public ResultResponse bizExceptionHandler(HttpServletRequest req, BizException e){
  15. logger.error("发生业务异常!原因是:{}",e.getErrorMsg());
  16. return ResultResponse.error(e);
  17. }
  18. /**
  19. * 处理空指针的异常
  20. */
  21. @ExceptionHandler(value =NullPointerException.class)
  22. public ResultResponse exceptionHandler(HttpServletRequest req, NullPointerException e){
  23. logger.error("发生空指针异常!原因是:",e);
  24. return ResultResponse.error(ExceptionEnum.BODY_NOT_MATCH);
  25. }
  26. /**
  27. * 处理其他异常
  28. */
  29. @ExceptionHandler(value =Exception.class)
  30. public ResultResponse exceptionHandler(HttpServletRequest req, Exception e){
  31. logger.error("未知异常!原因是:",e);
  32. return ResultResponse.error(ExceptionEnum.INTERNAL_SERVER_ERROR);
  33. }
  34. }

4. 创建测试demoController

  1. /**
  2. * @author ml
  3. */
  4. @RestController
  5. @RequestMapping("/demo")
  6. public class DemoController {
  7. /**
  8. * 抛出自定义异常
  9. */
  10. @RequestMapping("/demo")
  11. public String demo(){
  12. throw new BizException("-1","aaa");
  13. }
  14. /**
  15. * 抛出特定类型异常 空指针
  16. */
  17. @RequestMapping("/demo1")
  18. public String demo1(){
  19. String a = null;
  20. a.equals("333");
  21. return "";
  22. }
  23. }

5. 进行测试

5.1 自定义异常测试

image.png
image.png

5.2 特定类型异常

image.png
image.png