• @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,"用户名不能为空");
    }
    }
  • 相关阅读:
    java内部类与其他类变量之间的调用方式
    java线程数设置和系统cpu的关系
    IDEA设置方法自动显示参数提示
    (十)学生课程表查询
    (九)协处理器
    (八)filter的使用
    (七)多线程写入数据
    (六)mapreduce和Hbase集成
    (五)阅读推荐
    (四)region代码实现
  • 原文地址:https://www.cnblogs.com/gemiaomiao/p/10509640.html
Copyright © 2020-2023  润新知