SpringBoot 自定义错误处理器

SpringBoot默认情况下,当handlernotfound的情况下,没有直接报错,而是通过向tomcat设置错误报告属性,然后tomcat发现http status=404,就查找默认:/error 这个路径也就是BasicErrorController来进行错误的处理。这种情况下,我们用了@ControllerAdvice自定义错误处理没有生效,因为默认没有抛出异常。

解决方式:

    @Bean
    public ServletRegistrationBean dispatcherRegistration(DispatcherServlet dispatcherServlet) {
        ServletRegistrationBean registration = new ServletRegistrationBean(dispatcherServlet);
        dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
        return registration;
    }

但是,默认情况下,静态资源handler的拦截url是/**,所以访问一定不会存在NoHandlerFoundException,所以我们需要在配置文件中,指定url拦截的 static-path-pattern

spring.mvc.static-path-pattern=/public

这样,我们的@ControllerAdvice注解的ExceptionHandler就能处理404错误了。


当然,除了上面的方法,还有一种建议的做法,就是自己实现ErrorController。这样,springboot就不会自动创建BasicErrorController了,就会调用我们自己实现的Controller。

code:

/**
 * 通用错误处理器.
 * @author Wang.ch
 *
 */
@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class ControllerExceptionHandler extends AbstractErrorController {
    public ControllerExceptionHandler(ErrorAttributes errorAttributes) {
        super(errorAttributes);
    }
    private static final Logger log = LoggerFactory.getLogger(ControllerExceptionHandler.class);
    @Value("${server.error.path:${error.path:/error}}")
    private static String errorPath = "/error";

    /**
     * 500错误.
     * @param req
     * @param rsp
     * @param ex
     * @return
     * @throws Exception
     */
    @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public ModelAndView serverError(HttpServletRequest req, HttpServletResponse rsp, Exception ex) throws Exception {
        AntPathRequestMatcher matcher = new AntPathRequestMatcher("/api/**");
        if (matcher.matches(req)) {
            log.error("!!! request uri:{} from {} server exception:{}", req.getRequestURI(), RequestUtil.getIpAddress(req), ex.getMessage());
            ObjectMapper mapper = new ObjectMapper();
            mapper.setSerializationInclusion(Include.NON_NULL);
            String msg = mapper.writeValueAsString(BaseResponse.newFail(BaseResponse.STATUS_ERROR, "系统繁忙,请稍候重试"));
            return handleJSONError(rsp, msg, HttpStatus.OK);
        } else {
            throw ex;
        }
    }

    /**
     * 404的拦截.
     * @param request
     * @param response
     * @param ex
     * @return
     * @throws Exception
     */
    @ResponseStatus(code = HttpStatus.NOT_FOUND)
    @ExceptionHandler(NoHandlerFoundException.class)
    public ResponseEntity notFound(HttpServletRequest request, HttpServletResponse response, Exception ex) throws Exception {
            log.error("!!! request uri:{} from {} not found exception:{}", request.getRequestURI(), RequestUtil.getIpAddress(request), ex.getMessage());
            ObjectMapper mapper = new ObjectMapper();
            mapper.setSerializationInclusion(Include.NON_NULL);
            String msg = mapper.writeValueAsString(BaseResponse.newFail(BaseResponse.STATUS_BADREQUEST, "你访问的资源不存在"));
            handleJSONError(response, msg, HttpStatus.OK);
            return null;
    }

    /**
     * 参数不完整错误.
     * @param req
     * @param rsp
     * @param ex
     * @return
     * @throws Exception
     */
    @ResponseStatus(code = HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ModelAndView methodArgumentNotValidException(HttpServletRequest req, HttpServletResponse rsp, MethodArgumentNotValidException ex) throws Exception {
        AntPathRequestMatcher matcher = new AntPathRequestMatcher("/api/**");
        if (matcher.matches(req)) {
            BindingResult result = ex.getBindingResult();
            List fieldErrors = result.getFieldErrors();
            StringBuffer msg = new StringBuffer();
            fieldErrors.stream().forEach(fieldError -> {
                msg.append("[" + fieldError.getField() + "," + fieldError.getDefaultMessage() + "]");
            });
            ObjectMapper mapper = new ObjectMapper();
            mapper.setSerializationInclusion(Include.NON_NULL);
            String json = mapper.writeValueAsString(BaseResponse.newFail(BaseResponse.STATUS_BADREQUEST, "参数不合法:" + msg.toString()));
            return handleJSONError(rsp, json, HttpStatus.OK);
        } else {
            throw ex;
        }
    }

    @RequestMapping
    @ResponseBody
    public ResponseEntity handleErrors(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpStatus status = getStatus(request);
        if (status == HttpStatus.NOT_FOUND) {
            return notFound(request, response, null);
        }
        return handleErrors(request, response);
    }

    @RequestMapping(produces = "text/html")
    public ModelAndView handleHtml(HttpServletRequest request, HttpServletResponse response) throws Exception {
        return null;
    }

    protected ModelAndView handleViewError(String url, String errorStack, String errorMessage, String viewName) {
        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", errorStack);
        mav.addObject("url", url);
        mav.addObject("msg", errorMessage);
        mav.addObject("timestamp", new Date());
        mav.setViewName(viewName);
        return mav;
    }

    protected ModelAndView handleJSONError(HttpServletResponse rsp, String errorMessage, HttpStatus status) throws IOException {
        rsp.setCharacterEncoding("UTF-8");
        rsp.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        rsp.setStatus(status.value());
        PrintWriter writer = rsp.getWriter();
        writer.write(errorMessage);
        writer.flush();
        writer.close();
        return null;
    }

    @Override
    public String getErrorPath() {
        return errorPath;
    }
}

你可能感兴趣的:(SpringBoot 自定义错误处理器)