手机网站下拉列表,苏州做网站的公司哪家最好,wordpress仪表盘访问不了,内江手机网站建设在使用 servlet 过滤器时 发现异常报错 不准确#xff0c;定义的 全局异常处理 好像失效了#xff0c;过滤器里报错每次都会返回 状态码 #xff1a;500 错误信息为 “Internal Server Error” 真正的异常只能输出的控制台#xff0c;抛出不到前端。 问题#xff1a; 一般…在使用 servlet 过滤器时 发现异常报错 不准确定义的 全局异常处理 好像失效了过滤器里报错每次都会返回 状态码 500 错误信息为 “Internal Server Error” 真正的异常只能输出的控制台抛出不到前端。 问题 一般springBoot自带的全局异常捕获机制都是在业务层发生的异常来进行捕获的因为过滤器的执行顺序是在全局异常机制启动之前执行的所以一旦过滤器中发生异常全局异常捕获机制无法使用
以下是解决方案 在过滤器中try-catch掉需要捕获的异常返回自定义信息 使用 HttpServletResponse 响应体 直接返回前端错误信息 Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {HttpServletRequest httpServletRequest (HttpServletRequest) request;HttpServletResponse httpServletResponse (HttpServletResponse) response;try {//写一些比如 token的异常 这里可以捕获}catch (KuaiJingRuntimeException ke){try {WlUtils.getOutException(httpServletResponse,R.fail(ke.getMessage()));} catch (Exception e) {throw new RuntimeException(e);}return;}}R.fail r 就是返回前端的结构体 工具类 public static void getOutException(HttpServletResponse response,R r) throws Exception {response.setContentType(application/json;charsetUTF-8);PrintWriter out response.getWriter();String jsonObject JSON.toJSONString(r);out.println(jsonObject);out.flush();out.close();}