zoukankan      html  css  js  c++  java
  • @ControllerAdvice + @ExceptionHandler 全局处理 Controller 层异常

    1.自定义异常处理类

    **
    * 自定义异常处理类
    * 针对不同的异常自定义不同的方法
    * 环绕通知
    * 切面:针对所有的controller中抛出的异常
    * 若使用@ControllerAdvice,则不会自动转换为JSON格式
    */
    @RestControllerAdvice
    public class RestExceptionHandler {

    /**
    * 业务异常处理
    * @param e
    * @return ErrorInfo
    */
    @ExceptionHandler({BaseBusinessException.class})
    public ErrorInfo BusinessExceptionHandler(BaseBusinessException e) {
    return new ResponseResultUtil().error(e.getCode(), e.getMessage());
    }
    }

    2.定义一个用于返回页面结果信息的VO对象类:ErrorInfo
    public class ErrorInfo {
    private Integer code;
    private String message;

    public ErrorInfo(){};

    public ErrorInfo(Integer code, String message) {
    super();
    this.code = code;
    this.message = message;

    }
    public Integer getCode() {
    return code;
    }
    public void setCode(Integer code) {
    this.code = code;
    }
    public String getMessage() {
    return message;
    }
    public void setMessage(String message) {
    this.message = message;
    }
    }
    
    
    3.封装一个基础业务异常类(让所有自定义业务异常类 继承此 基础类):BaseBusinessException
    /**
    * 类名称: BaseBusinessException <br>
    * 类描述: 业务异常父类<br>
    * 创建人:GMM <br>
    * date 2019/3/11<br>
    */
    public class BaseBusinessException extends RuntimeException {

    private Integer code;

    // 给子类用的方法
    public BaseBusinessException(HttpStatus httpStatus) {
    this(httpStatus.value(),httpStatus.getReasonPhrase());
    }

    public BaseBusinessException(Integer code,String message) {
    super(message);
    this.code = code;
    }

    public Integer getCode() {
    return code;
    }

    public void setCode(Integer code) {
    this.code = code;
    }
    }
    4.service 层抛出

    @Service
    public class UserLoginServiceImpl implements UserLoginService {

    @Autowired
    private UserLoginRepsitory userLoginRepsitory;

    @Transactional
    @Override
    public boolean login(String userCode, String password) {
    Employee employee=userLoginRepsitory.getEmployeeByCode(userCode);
    if(StringUtils.isBlank(userCode)){
    throw new BaseBusinessException(101,"用户名不能为空");
    }
    }
  • 相关阅读:
    题解【LOJ10094】「一本通 3.5 练习 2」消息的传递
    Codeforces Round #644 (Div. 3) 题解
    题解【洛谷P3627】[APIO2009]抢掠计划
    HDU-4416 Good Article Good sentence 后缀自动机
    HDU-6274 Master of Sequence 数学+二分
    Codeforces 666E Forensic Examination 广义后缀自动机+线段树合并+树上倍增
    HDU-5955 Guessing the Dice Roll AC自动机+高斯消元
    Codeforces 1437G Death DBMS AC自动机
    Codeforces 1037H Security sam+线段树合并
    2020ICPC·小米 网络选拔赛第一场 E-Phone Network 线段树
  • 原文地址:https://www.cnblogs.com/gemiaomiao/p/10509640.html
Copyright © 2011-2022 走看看