当前位置:   article > 正文

JAVA全局异常捕获

java全局异常捕获

目录

一、概述

二、实现效果

三、异常枚举类

四、异常类

五、异常处理类


一、概述

实现的功能如下:

1.全局捕获异常,当出现错误抛出一个友好的提示给前端。

2.手动在指定处直接抛出一个有好的提示,终止当前操作。

二、实现效果

手动抛出异常,在那个层都可以直接捕获异常,只要符合条件。

 实现效果

除此之外,只要程序出现异常,可以设定一个默认的提示,返回给前端。

三、异常枚举类

主要用于直接调用枚举类,传递给定的信息便于维护。

  1. public enum FrontMonitorErrorCode {
  2. NULL_TENANT_KEY("001","tenantKey为空"),
  3. UNKNOWN_ERROR("002","未知错误,请联系管理员");
  4. private String value;
  5. private String desc;
  6. private FrontMonitorErrorCode(String value, String desc) {
  7. this.setValue(value);
  8. this.setDesc(desc);
  9. }
  10. public String getValue() {
  11. return value;
  12. }
  13. public void setValue(String value) {
  14. this.value = value;
  15. }
  16. public String getDesc() {
  17. return desc;
  18. }
  19. public void setDesc(String desc) {
  20. this.desc = desc;
  21. }
  22. @Override
  23. public String toString() {
  24. return "[" + this.value + "]" + this.desc;
  25. }
  26. }

四、异常类

  1. public class FrontMonitorException extends RuntimeException {
  2. private static final long serialVersionUID = 1L;
  3. public FrontMonitorException(FrontMonitorErrorCode errorCode) {
  4. super(errorCode.toString());
  5. }
  6. }

五、异常处理类

主要用于返回异常信息。

  1. import org.springframework.web.bind.annotation.ControllerAdvice;
  2. import org.springframework.web.bind.annotation.ExceptionHandler;
  3. import org.springframework.web.bind.annotation.ResponseBody;
  4. /**
  5. *
  6. * @Date:Created in 11:31 2022/3/8
  7. */
  8. @ControllerAdvice
  9. public class FrontMonitorExceptionHandler {
  10. @ExceptionHandler(value = FrontMonitorException.class)
  11. @ResponseBody
  12. public String exceptionHandler(FrontMonitorException e) {
  13. return e.getMessage();
  14. }
  15. @ExceptionHandler(value = Exception.class)
  16. @ResponseBody
  17. public String baseHandler() {
  18. return "服务器出现异常,请联系管理员!";
  19. }
  20. }

然后在需要的地方直接抛出异常就可以了。

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/372856
推荐阅读
相关标签
  

闽ICP备14008679号