• SpringBoot全局异常配置


    1、实现方式定义一个全局异常配置类,使用@RestControllerAdvice注解

    在使用方法上用
    @ExceptionHandler(value = BizException.class)配合使用,使其异常提示作用

    2、需要定义一个统一结果返回类,如下代码

    1. @Data
    2. @Slf4j
    3. @ToString
    4. public class CommonResult<T> {
    5. /**
    6. * 状态码
    7. */
    8. private long code;
    9. /**
    10. * 提示信息
    11. */
    12. private String message;
    13. /**
    14. * 数据封装
    15. */
    16. private T data;
    17. protected CommonResult() {
    18. }
    19. protected CommonResult(long code, String message, T data) {
    20. this.code = code;
    21. this.message = message;
    22. this.data = data;
    23. }
    24. /**
    25. * 成功返回结果
    26. *
    27. * @param data 获取的数据
    28. */
    29. public static <T> CommonResult<T> success(T data) {
    30. return new CommonResult<T>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), data);
    31. }
    32. /**
    33. * 成功返回结果
    34. *
    35. * @param data 获取的数据
    36. * @param message 提示信息
    37. */
    38. public static <T> CommonResult<T> success(T data, String message) {
    39. return new CommonResult<T>(ResultCode.SUCCESS.getCode(), message, data);
    40. }
    41. /**
    42. * 失败返回结果
    43. * @param errorCode 错误码
    44. */
    45. public static <T> CommonResult<T> failed(IErrorCode errorCode) {
    46. return new CommonResult<T>(errorCode.getCode(), errorCode.getMessage(), null);
    47. }
    48. /**
    49. * 失败返回结果
    50. * @param errorCode 错误码
    51. * @param message 错误信息
    52. */
    53. public static <T> CommonResult<T> failed(IErrorCode errorCode,String message) {
    54. return new CommonResult<T>(errorCode.getCode(), message, null);
    55. }
    56. /**
    57. * 失败返回结果
    58. * @param message 提示信息
    59. */
    60. public static <T> CommonResult<T> failed(String message) {
    61. return new CommonResult<T>(ResultCode.FAILED.getCode(), message, null);
    62. }
    63. /**
    64. * 失败返回结果
    65. */
    66. public static <T> CommonResult<T> failed() {
    67. return failed(ResultCode.FAILED);
    68. }
    69. /**
    70. * 参数验证失败返回结果
    71. */
    72. public static <T> CommonResult<T> validateFailed() {
    73. return failed(ResultCode.VALIDATE_FAILED);
    74. }
    75. /**
    76. * 参数验证失败返回结果
    77. * @param message 提示信息
    78. */
    79. public static <T> CommonResult<T> validateFailed(String message) {
    80. return new CommonResult<T>(ResultCode.VALIDATE_FAILED.getCode(), message, null);
    81. }
    82. /**
    83. * 未登录返回结果
    84. */
    85. public static <T> CommonResult<T> unauthorized(T data) {
    86. return new CommonResult<T>(ResultCode.UNAUTHORIZED.getCode(), ResultCode.UNAUTHORIZED.getMessage(), data);
    87. }
    88. /**
    89. * 未授权返回结果
    90. */
    91. public static <T> CommonResult<T> forbidden(T data) {
    92. return new CommonResult<T>(ResultCode.FORBIDDEN.getCode(), ResultCode.FORBIDDEN.getMessage(), data);
    93. }

    3、需要定义一个统一的错误吗接口,异常枚举类来实现

    1. /**
    2. * 错误码接口
    3. */
    4. public interface IErrorCode {
    5. /**
    6. * 返回码
    7. */
    8. long getCode();
    9. /**
    10. * 返回信息
    11. */
    12. String getMessage();
    13. }
    1. /**
    2. * 统一返回结果枚举定义
    3. */
    4. public enum ResultCode implements IErrorCode {
    5. SUCCESS(200, "操作成功"),
    6. FAILED(500, "操作失败"),
    7. VALIDATE_FAILED(404, "参数检验失败"),
    8. UNAUTHORIZED(401, "暂未登录或token已经过期"),
    9. FORBIDDEN(403, "没有相关权限");
    10. private long code;
    11. private String message;
    12. private ResultCode(long code, String message) {
    13. this.code = code;
    14. this.message = message;
    15. }
    16. @Override
    17. public long getCode() {
    18. return code;
    19. }
    20. @Override
    21. public String getMessage() {
    22. return message;
    23. }

    4、自定义业务异常,在业务异常时使用抛出,在全局异常里面处理捕获返回给前端

    1. /**
    2. * 自定义业务异常
    3. */
    4. public class BizException extends RuntimeException{
    5. private IErrorCode errorCode;
    6. public BizException(Throwable cause) {
    7. super(cause);
    8. }
    9. public BizException(IErrorCode code) {
    10. super(code.getMessage());
    11. this.errorCode = code;
    12. }
    13. public BizException(String message) {
    14. super(message);
    15. }
    16. public BizException(String message, Throwable cause) {
    17. super(message, cause);
    18. }
    19. public IErrorCode getErrorCode() {
    20. return errorCode;
    21. }
    22. }

    5、定义全局异常处理

    1. /**
    2. * 全局异常处理
    3. */
    4. @RestControllerAdvice
    5. public class GlobalExceptionHandler {
    6. /**
    7. * 业务异常
    8. * @param e
    9. * @return
    10. */
    11. @ExceptionHandler(value = BizException.class)
    12. public CommonResult handle(BizException e) {
    13. if (e.getErrorCode() != null) {
    14. return CommonResult.failed(e.getErrorCode());
    15. }
    16. return CommonResult.failed(e.getMessage());
    17. }
    18. /**
    19. * 将请求体解析并绑定到 java bean 时,如果出错,则抛出 MethodArgumentNotValidException 异常
    20. * @param e
    21. * @return
    22. */
    23. @ExceptionHandler(value = MethodArgumentNotValidException.class)
    24. public CommonResult handleValidException(MethodArgumentNotValidException e) {
    25. BindingResult bindingResult = e.getBindingResult();
    26. String message = null;
    27. if (bindingResult.hasErrors()) {
    28. FieldError fieldError = bindingResult.getFieldError();
    29. if (fieldError != null) {
    30. message = fieldError.getField()+fieldError.getDefaultMessage();
    31. }
    32. }
    33. return CommonResult.validateFailed(message);
    34. }
    35. /**
    36. * 表单绑定到 java bean 出错时,绑定参数校验异常
    37. * @param e
    38. * @return
    39. */
    40. @ExceptionHandler(value = BindException.class)
    41. public CommonResult handleValidException(BindException e) {
    42. BindingResult bindingResult = e.getBindingResult();
    43. String message = null;
    44. if (bindingResult.hasErrors()) {
    45. FieldError fieldError = bindingResult.getFieldError();
    46. if (fieldError != null) {
    47. message = fieldError.getField()+fieldError.getDefaultMessage();
    48. }
    49. }
    50. return CommonResult.validateFailed(message);
    51. }
    52. @ExceptionHandler(value = SQLSyntaxErrorException.class)
    53. public CommonResult handleSQLSyntaxErrorException(SQLSyntaxErrorException e) {
    54. String message = e.getMessage();
    55. if (StrUtil.isNotEmpty(message) && message.contains("denied")) {
    56. message = "演示环境暂无修改权限,如需修改数据可本地搭建后台服务!";
    57. }
    58. return CommonResult.failed(message);
    59. }
    60. /**
    61. * 必填校验参数缺失错误
    62. * @param e
    63. * @return
    64. */
    65. @ExceptionHandler(value = MissingServletRequestParameterException.class)
    66. public CommonResult handleMissingServletException(MissingServletRequestParameterException e) {
    67. String message = e.getMessage();
    68. if (StrUtil.isNotEmpty(message)) {
    69. return CommonResult.validateFailed(message);
    70. }
    71. return CommonResult.validateFailed(message);
    72. }
    73. }

    断言设置,可以在抛出异常时使代码更简洁清晰,其中加了一些true、false的判断

    作用等同于throw new BizException(“msg”);

    1. package com.example.common.util;
    2. import cn.hutool.core.collection.CollUtil;
    3. import cn.hutool.core.map.MapUtil;
    4. import cn.hutool.core.util.ObjectUtil;
    5. import cn.hutool.core.util.StrUtil;
    6. import com.example.common.api.IErrorCode;
    7. import com.example.common.exception.BizException;
    8. import lombok.NoArgsConstructor;
    9. import java.util.Collection;
    10. import java.util.Map;
    11. import java.util.Objects;
    12. /**
    13. * 断言
    14. */
    15. @NoArgsConstructor
    16. public class BizAssert {
    17. public static void equals(IErrorCode errorEnum, Object obj1, Object obj2, Object... params) {
    18. if (!Objects.equals(obj1, obj2)) {
    19. failure(errorEnum, params);
    20. }
    21. }
    22. public static void isTrue(IErrorCode errorEnum, boolean condition, Object... params) {
    23. if (!condition) {
    24. failure(errorEnum, params);
    25. }
    26. }
    27. public static void isFalse(IErrorCode errorEnum, boolean condition, Object... params) {
    28. if (condition) {
    29. failure(errorEnum, params);
    30. }
    31. }
    32. public static void isNull(IErrorCode errorEnum, Object condition, Object... params) {
    33. if (ObjectUtil.isNotNull(condition)) {
    34. failure(errorEnum, params);
    35. }
    36. }
    37. public static void notNull(IErrorCode errorEnum, Object condition, Object... params) {
    38. if (ObjectUtil.isNull(condition)) {
    39. failure(errorEnum, params);
    40. }
    41. }
    42. public static void equals(String message, Object obj1, Object obj2, Object... params) {
    43. if (!Objects.equals(obj1, obj2)) {
    44. failure(message, params);
    45. }
    46. }
    47. public static void isTrue(String message, boolean condition, Object... params) {
    48. if (!condition) {
    49. failure(message, params);
    50. }
    51. }
    52. public static void isFalse(String message, boolean condition, Object... params) {
    53. if (condition) {
    54. failure(message, params);
    55. }
    56. }
    57. public static void isNull(String message, Object condition, Object... params) {
    58. if (ObjectUtil.isNotNull(condition)) {
    59. failure(message, params);
    60. }
    61. }
    62. public static void notNull(String message, Object condition, Object... params) {
    63. if (ObjectUtil.isNull(condition)) {
    64. failure(message, params);
    65. }
    66. }
    67. /**
    68. *

    69. * 失败结果
    70. *

    71. * @param errorCode 异常错误码
    72. */
    73. public static void failure(IErrorCode errorCode, Object... params) {
    74. failure(errorCode.getMessage(),params);
    75. }
    76. /**
    77. * 失败
    78. * @param message
    79. * @param params
    80. */
    81. public static void failure(String message, Object... params) {
    82. throw new BizException(StrUtil.format(message, params));
    83. }
    84. /**
    85. * 数组为空通过msg
    86. * @param message
    87. * @param array
    88. * @param params
    89. */
    90. public static void notEmpty(String message, Object[] array, Object... params) {
    91. if (ObjectUtil.isEmpty(array)) {
    92. failure(message, params);
    93. }
    94. }
    95. /**
    96. * 数组为空通过errorCode
    97. * @param errorCode
    98. * @param array
    99. * @param params
    100. */
    101. public static void notEmpty(IErrorCode errorCode, Object[] array, Object... params) {
    102. if (ObjectUtil.isEmpty(array)) {
    103. failure(errorCode, params);
    104. }
    105. }
    106. /**
    107. * 集合为空
    108. * @param errorEnum
    109. * @param collection
    110. * @param params
    111. */
    112. public static void notEmpty(IErrorCode errorEnum, Collection collection, Object... params) {
    113. if (CollUtil.isEmpty(collection)) {
    114. failure(errorEnum, params);
    115. }
    116. }
    117. /**
    118. * map为空
    119. * @param errorEnum
    120. * @param map
    121. * @param params
    122. */
    123. public static void notEmpty(IErrorCode errorEnum, Map map, Object... params) {
    124. if (MapUtil.isEmpty(map)) {
    125. failure(errorEnum, params);
    126. }
    127. }
    128. /**集合不能为空
    129. * @param errorEnum
    130. * @param collection
    131. * @param params
    132. */
    133. public static void isEmpty(IErrorCode errorEnum, Collection collection, Object... params) {
    134. if (CollUtil.isNotEmpty(collection)) {
    135. failure(errorEnum, params);
    136. }
    137. }
    138. /**
    139. * map不为空
    140. * @param errorEnum
    141. * @param map
    142. * @param params
    143. */
    144. public static void isEmpty(IErrorCode errorEnum, Map map, Object... params) {
    145. if (MapUtil.isNotEmpty(map)) {
    146. failure(errorEnum, params);
    147. }
    148. }
    149. public static void notEmpty(String message, Collection collection, Object... params) {
    150. if (CollUtil.isEmpty(collection)) {
    151. failure(message, params);
    152. }
    153. }
    154. public static void notEmpty(String message, Map map, Object... params) {
    155. if (MapUtil.isEmpty(map)) {
    156. failure(message, params);
    157. }
    158. }
    159. public static void isEmpty(String message, Collection collection, Object... params) {
    160. if (CollUtil.isNotEmpty(collection)) {
    161. failure(message, params);
    162. }
    163. }
    164. public static void isEmpty(String message, Map map, Object... params) {
    165. if (MapUtil.isNotEmpty(map)) {
    166. failure(message, params);
    167. }
    168. }
    169. }

  • 相关阅读:
    如何做bug分析 ?bug分析什么 ? 为什么要做bug分析 ?
    【LeetCode热题100】--102.二叉树的层序遍历
    【编程题】【Scratch三级】2021.03 加法出题机
    成员变量、静态成员变量、局部变量、常量的内存区域
    QPlainTextEdit等 自制 文本或者代码 编辑器控件 是如何 自定义 实现的?
    计算机网络八股
    码蹄集 - MT2140 - 双端队列
    (57、58)性能分析命令2
    Android 12(S) 图像显示系统 - SurfaceFlinger 之 VSync - 中篇(十七)
    MFC 鼠标悬停提示框
  • 原文地址:https://blog.csdn.net/qq_31450641/article/details/133947452