web项目中过滤器抛出的异常不直接被全局异常处理捕获,不过我们可以选择其他办法达到目录
实例代码
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)servletRequest;
String reqUrl = request.getRequestURI();
log.info(“当前请求:{}”,reqUrl);
if (StringUtils.equals(reqUrl, LOGIN_URL)) {
filterChain.doFilter(servletRequest, servletResponse);
return;
}
String authzHeader = getAuthzHeader(servletRequest);
if(StringUtils.isBlank(authzHeader)){
NeedLoginException exception = new NeedLoginException(“请先登录!”);
request.setAttribute(CommonConsts.NEED_LOGIN_ERROR,exception);
throw exception;
}
boolean verify = JwtUtil.verify(authzHeader);
if(!verify){
NeedLoginException exception = new NeedLoginException(“无效token,请先登录!”);
request.setAttribute(CommonConsts.NEED_LOGIN_ERROR,exception);
throw exception;
}
import io.swagger.annotations.Api;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
@RestController
@Api(tags = “拦截Filter抛出的异常”)
public class ErrorController extends BasicErrorController {
public ErrorController() {
super(new DefaultErrorAttributes(), new ErrorProperties());
}
public ErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties) {
super(errorAttributes, errorProperties);
}
public ErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties, List<ErrorViewResolver> errorViewResolvers) {
super(errorAttributes, errorProperties, errorViewResolvers);
}
@RequestMapping
@Override
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
Object obj = request.getAttribute(CommonConsts.NEED_LOGIN_ERROR);
Map<String, Object> body = this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.ALL));
if (null != obj) {
/**
* 设置登录跳转错误码
*/
body.put(“status”,HttpStatus.UNAUTHORIZED);
}
HttpStatus status = this.getStatus(request);
return new ResponseEntity(body, status);
}
}
{
“timestamp”: “2022-01-10 14:08:08”,
“status”: 401,
“error”: “Internal Server Error”,
“message”: “无效token,请重新登录”,
“path”: “/xxxxx”
}
————————————————
版权声明:本文为CSDN博主「朽木要自雕」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/fenfenguai/article/details/122408992