美文网首页
springboot异常

springboot异常

作者: 阿涩_d210 | 来源:发表于2019-05-31 16:30 被阅读0次

springboot

参考了各个大佬的写法,因为之前在本地写的文档,但是没有记录链接,如有侵权,请联系本人

springboot异常处理

异常处理的最佳实践,主要遵循几点

  1. 尽量不要在代码里面写try catch finally
  2. 异常尽量要直观,防止被他人误解
  3. 将异常分为以下几类:业务异常,登录状态无效异常,未授权异常,系统异常
  4. 可以在某个特定的controller中处理异常,也可以使用全局异常处理器。尽量使用全局异常处理器

异常处理流程:

  1. 首先自定义一个自己的异常类CustomeException,继承RuntimeException,再写一个异常管理类ExceptionManager,用来抛出自定义的异常
  2. 然后使用spring提供的注解@RestControllerAdvice或者@ControllerAdvice写一个统一异常处理的类,在这个类中写一个带一个@ExceptionHandler(Exception.calss)注解的方法,这个方法接收到所有抛出的异常,在方法内我们可以写自己的异常处理逻辑
  3. 如果参数是CustomerException类型,我们就自定义异常字典的错误信息,如果是其他类型的异常就返回系统异常

talk is cheap,show me the code

  1. 自定义的异常类

    @Data
    @NoArgsConstructor
    public class CustomException extends RuntimeException {

    public CustomException(String code, String msg) {
        super(code);
        this.code = code;
        this.msg = msg;
    }
    
    private String code;
    
    private String msg;
    

    }

  2. 异常管理类

    @Component
    public class ExceptionManager {

    @Resource
    Environment environment;
    
    public CustomException create(String code) {
        return new CustomException(code, environment.getProperty(code));
    }
    

    }

    Environment 是spring的环境类,会包含所有properties文件的键值对

  1. 异常字典

sso异常测试

EC00001=SSO的WEB层错误

需要加载到spring的环境中,我是用配置类加载的,方式如下:

 @Component
 @PropertySource(value = {"exception.properties"}, encoding = "UTF-8")
 public class LoadProperty {

 }
  1. 全局异常捕获类

    @RestControllerAdvice
    public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ApiResult handlerException(Exception e) {

     //如果是自定义的异常,返回对应的错误信息
     if (e instanceof CustomException) {
         e.printStackTrace();
         CustomException exception = (CustomException) e;
         return ApiResult.error(exception.getCode(), exception.getMsg());
     } else {
         //如果不是已知异常,返回系统异常
         e.printStackTrace();
         return ApiResult.error("SYS_EXCEPTION", "系统异常");
     }
    

    }

}

  1. 使用示例

@RestController
@RequestMapping("/exception")
public class ExceptionController {

@Resource
ExceptionManager exceptionManager;

@RequestMapping("/controller")
public String exceptionInController() {
    if (true) {
        throw exceptionManager.create("EC00001");
    }
    return "controller exception!";
}

}

返回信息:

{
"code": "EC00001",
"msg": "SSO的WEB层错误"
}

相关文章

网友评论

      本文标题:springboot异常

      本文链接:https://www.haomeiwen.com/subject/xndgtctx.html