• 【Spring Boot】实现全局异常处理


    1.定义基础异常接口类

    1. /**
    2. * @description: 服务接口类
    3. * @author: MrVK
    4. * @date: 2021/4/19 21:39
    5. */
    6. public interface BaseErrorInfoInterface {
    7. /**
    8. * 错误码
    9. * @return
    10. */
    11. String getResultCode();
    12. /**
    13. * 错误描述
    14. * @return
    15. */
    16. String getResultMsg();
    17. }

    2.定义错误处理枚举类

    1. /**
    2. * @description: 异常处理枚举类
    3. * @author: MrVK
    4. * @date: 2021/4/19 21:41
    5. * @version: v1.0
    6. */
    7. public enum ExceptionEnum implements BaseErrorInfoInterface{
    8. // 数据操作错误定义
    9. SUCCESS("2000", "成功!"),
    10. BODY_NOT_MATCH("4000","请求的数据格式不符!"),
    11. SIGNATURE_NOT_MATCH("4001","请求的数字签名不匹配!"),
    12. NOT_FOUND("4004", "未找到该资源!"),
    13. INTERNAL_SERVER_ERROR("5000", "服务器内部错误!"),
    14. SERVER_BUSY("5003","服务器正忙,请稍后再试!");
    15. /**
    16. * 错误码
    17. */
    18. private final String resultCode;
    19. /**
    20. * 错误描述
    21. */
    22. private final String resultMsg;
    23. ExceptionEnum(String resultCode, String resultMsg) {
    24. this.resultCode = resultCode;
    25. this.resultMsg = resultMsg;
    26. }
    27. @Override
    28. public String getResultCode() {
    29. return resultCode;
    30. }
    31. @Override
    32. public String getResultMsg() {
    33. return resultMsg;
    34. }
    35. }

    3.自定义异常类

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

    4.自定义响应体类

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

    5.自定义全局异常处理

    1. /**
    2. * @description: 自定义异常处理
    3. * @author: MrVK
    4. * @date: 2021/4/19 21:51
    5. * @version: v1.0
    6. */
    7. @ControllerAdvice
    8. public class GlobalExceptionHandler {
    9. private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    10. /**
    11. * 处理自定义的业务异常
    12. * @param req
    13. * @param e
    14. * @return
    15. */
    16. @ExceptionHandler(value = BizException.class)
    17. @ResponseBody
    18. public ResultResponse bizExceptionHandler(HttpServletRequest req, BizException e){
    19. logger.error("发生业务异常!原因是:{}",e.getErrorMsg());
    20. return ResultResponse.error(e.getErrorCode(),e.getErrorMsg());
    21. }
    22. /**
    23. * 处理空指针的异常
    24. * @param req
    25. * @param e
    26. * @return
    27. */
    28. @ExceptionHandler(value =NullPointerException.class)
    29. @ResponseBody
    30. public ResultResponse exceptionHandler(HttpServletRequest req, NullPointerException e){
    31. logger.error("发生空指针异常!原因是:",e);
    32. return ResultResponse.error(ExceptionEnum.BODY_NOT_MATCH);
    33. }
    34. /**
    35. * 处理其他异常
    36. * @param req
    37. * @param e
    38. * @return
    39. */
    40. @ExceptionHandler(value =Exception.class)
    41. @ResponseBody
    42. public ResultResponse exceptionHandler(HttpServletRequest req, Exception e){
    43. logger.error("未知异常!原因是:",e);
    44. return ResultResponse.error(ExceptionEnum.INTERNAL_SERVER_ERROR);
    45. }
    46. }

    6.测试代码

    1. @PostMapping("/add")
    2. public boolean add(@RequestBody User user) {
    3. //如果姓名为空就手动抛出一个自定义的异常!
    4. if(user.getName()==null){
    5. throw new BizException("-1","用户姓名不能为空!");
    6. }
    7. return true;
    8. }
    9. @PutMapping("/update")
    10. public boolean update(@RequestBody User user) {
    11. //这里故意造成一个空指针的异常,并且不进行处理
    12. String str = null;
    13. str.equals("111");
    14. return true;
    15. }
    16. @DeleteMapping("/delete")
    17. public boolean delete(@RequestBody User user) {
    18. //这里故意造成一个异常,并且不进行处理
    19. Integer.parseInt("abc123");
    20. return true;
    21. }
    22. @GetMapping("/error")
    23. @ExceptionHandler(value = NumberFormatException.class)
    24. @ResponseBody
    25. public ResultResponse exceptionHandler(HttpServletRequest req, NumberFormatException e){
    26. logger.error("发生类型转换异常!原因是:",e);
    27. return ResultResponse.error(ExceptionEnum.PARAMS_NOT_CONVERT);
    28. }

    7.测试结果

  • 相关阅读:
    查分小程序,教学大作用
    Centos7宝塔部署python
    记录:树莓派 安装opencv 完整的艰辛过程
    Linux中通配符、shell元字符、转义符
    java计算商场折扣 判断体重 判断学生成绩等级 验证邮箱 demo
    【深度学习21天学习挑战赛】备忘篇:我们的神经网模型到底长啥样?——model.summary()详解
    Oozie 集成 Shell
    深入了解HTTP代理的工作原理
    Flask框架配置celery-[1]:flask工厂模式集成使用celery,可在异步任务中使用flask应用上下文,即拿即用,无需更多配置
    【Java】HashMap、HashTable和ConcurrentHashMap的区别
  • 原文地址:https://blog.csdn.net/Mr_VK/article/details/136438289