在需要处理异常的地方抛出异常即可,例如在登录拦截器中,判断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;
}
}