天下文章一大抄,#CSDN 上的答案几乎就是坑爹货,一旦对都是将异常信息 set
到 request
后再转发到自定义controller。
因此,错误的做法
将异常信息
set
到request
后再转发到自定义controller。
正确的做法
抛出异常
@WebFilter(urlPatterns = "/*", filterName = "xxxFilter") public class TestFilter implements Filter { // ........ // ...... @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest)servletRequest; ServletResponse response = servletResponse; String token = request.getHeader("token"); if (token == null || !token.equals("123")) { throw new BadRequestException("非法请求!"); } else { filterChain.doFilter(request, response); } } }
捕获方法
@RestController @Slf4j public class GlobalErrorController extends BasicErrorController { // ........ // ........ // ........ @Override @RequestMapping public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) { log.error("进入error处理器"); Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception"); if (throwable instanceof UtException) { UtException utException = (UtException) throwable; Integer statusCode = utException.getStatus().value(); return new ResponseEntity(new BaseResponse<>(statusCode, utException.getMessage(), null), utException.getStatus()); } else { return new ResponseEntity(new BaseResponse<>(500, "出现意料之外的错误", null), HttpStatus.valueOf(500)); } } }
目前尚无回复