很多时候,我们在项目中使用 Filter 过滤器的时候, 或多或少会有自定义的异常抛出, 但是当客户端访问接口时, 如果是直接使用Throw 抛出异常, 那么返回的结果 就会是 request 内部的 500 错误码。这是我如果想返回自己的code和一些msg的时候就不方便了。
所以,我们采用 继承 请求的基类,BasicRequestController ,创建一个自己的ErrorController, 然后重写 其中的 error方法即可。
代码如下
MyFilter:
@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest)servletRequest; HttpServletResponse response = (HttpServletResponse)servletResponse; if (!permitAllUrl(request,permitUrlConfiguration.getPermitUrlArray())) { CommonAuthHeader commonAuthHeader = new CommonAuthHeader(); Map<String, String> headerMap = getHeadersInfo(request); if(!CollectionUtils.isEmpty(headerMap)){ commonAuthHeader.setToken(headerMap.get("token")); commonAuthHeader.setVersion(headerMap.get("version")); commonAuthHeader.setPlatform(headerMap.get("platform")); } CommonResult<AppAccountInfo> availAccount = tokenService.getAvailAccount(commonAuthHeader.getToken(), commonAuthHeader.getVersion(), commonAuthHeader.getPlatform()); if(null != availAccount && availAccount.getCode() != CommonResult.SUCCESS){ //抛出自己的异常,方便ErrorController拦截 throw new OftenFiledException(JSONObject.toJSONString(availAccount)); } } chain.doFilter(request, response); }
ErrorController:
@RestController @Api(value = "filter错误处理", description = "filter错误处理") public class ErrorController extends BasicErrorController { public ErrorController() { super(new DefaultErrorAttributes(), new ErrorProperties()); } @Override @RequestMapping(produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) { Map<String, Object> body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL)); HttpStatus status = getStatus(request); String jsonCommonResult = body.get("message").toString(); //自定义的错误信息类 Ret ret = null; if(StringUtils.isEmpty(jsonCommonResult)) { CommonResult commonResult = JSONObject.parseObject(jsonCommonResult, CommonResult.class); ret = Ret.error(commonResult.getCode(), commonResult.getMsg()); } //OftenFiledException Filter抛出的自定义错误类 if (!Strings.isNullOrEmpty((String) body.get("exception")) && body.get("exception").equals(OftenFiledException.class.getName())) { body.put("status", HttpStatus.FORBIDDEN.value()); status = HttpStatus.FORBIDDEN; } return new ResponseEntity(ret, status); } @Override public String getErrorPath() { return super.getErrorPath(); } }
第一次写的博客, 样式有点丑陋, 不过希望能帮助需要帮助的人。