SpringBoot开发(4)——统一处理异常

  1. 在cxsbg包下建立exception包,在exception包中新建MyControllerAdvice类,并加上注解,类中写具体的异常处理方法
    package com.cxsbg.exception;
    
    import com.cxsbg.domain.ResponseResult;
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    @ControllerAdvice //注入,处理异常
    public class MyControllerAdvice {
        //自定义方法处理异常
        @ExceptionHandler(RuntimeException.class)//指定处理哪类异常
        @ResponseBody //返回的结果放回相应体中,所以要加此注解
        public ResponseResult handlerException(Exception e){
            //获得异常消息
            String message = e.getMessage();
            //将异常消息存入ResponseResult的msg属性中
            ResponseResult responseResult = new ResponseResult(300, message);
            //返回ResponseResult,到时候能转换成json存入响应体中
            return responseResult;
        }
    }
    
  2. 在需要处理异常的地方抛出异常即可,例如在登录拦截器中,判断token时,即可抛出异常
    package com.cxsbg.interceptor;
    
    import com.cxsbg.utils.JwtUtil;
    import io.jsonwebtoken.Claims;
    import org.springframework.stereotype.Component;
    import org.springframework.util.StringUtils;
    import org.springframework.web.servlet.HandlerInterceptor;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    @Component //注入
    //实现登录拦截器,验证token是否有效,如果有效就放行
    public class LoginInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            //获取请求头中的token
            String token = request.getHeader("token");
            //判断token是否为空,如果为空,说明未登录,不放行
            if(!StringUtils.hasText(token)){
                //发送错误码
                //response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                throw new RuntimeException("未登录");
                //return false;
            }
            //判断token是否有效,如果无效,不放行
            try {
                Claims claims = JwtUtil.parseJWT(token);
                String subject = claims.getSubject();
                System.out.println(subject);
            }catch (Exception e){
                //发送错误码
    //            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    //            return false;
                throw new RuntimeException("未登录");
            }
            return true;
        }
    }
    

发表评论

邮箱地址不会被公开。 必填项已用*标注