美文网首页
Spring boot 配置错误捕获

Spring boot 配置错误捕获

作者: 田文健 | 来源:发表于2019-11-06 15:31 被阅读0次

一种是下面这种方式:

@ControllerAdvice
@Slf4j
public class ExceptionHandler {


    /**
     * 判断错误是否是已定义的已知错误,不是则由未知错误代替,同时记录在log中
     *
     * @param e
     * @return
     */
    @org.springframework.web.bind.annotation.ExceptionHandler(value = Exception.class)
    @ResponseBody
    public R getException(Exception e) {
        if (e instanceof BusinessException) {
            BusinessException exception = (BusinessException) e;
            return ResultUtil.error(exception.getCode(), exception.getErrMsg());
        } else {
            log.error("【系统异常】{}", e);
            return ResultUtil.error(ResultEnum.UNKNOWN_ERROR);
        }
    }
}

ControllerAdvice 是基于AOP实现的一种织入的处理方式,它支持:
方法型注解@ExceptionHandler,用于捕获Controller中抛出的指定类型的异常,从而达到不同类型的异常区别处理的目的;
方法型注解@InitBinder,用于request中自定义参数解析方式进行注册,从而达到自定义指定格式参数的目的;
方法型注解@ModelAttribute,表示其标注的方法将会在目标Controller方法执行之前执行。

@ExceptionHandler 可以指定异常类型,结合ResponseBody可以直接返回json的数据。当然也可以使用其他数据逻辑。

这种只是对bean中出现的错误进行捕获,有一些局限性。比如Spring MVC或者容器本身的异常捕获不到,那么需要下面的方法。

@Controller
@Slf4j
public class MyErrorController  implements ErrorController {

    private static final String ERROR_PATH = "/error";

    @RequestMapping(ERROR_PATH)
    public void error(HttpServletRequest request, HttpServletResponse response) {
        //获取statusCode:401,404,500
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        log.info("发生了页面错误:" + statusCode + ":" + request.getRequestURI());
        try {
            response.reset();
            response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
            response.setContentType(MediaType.TEXT_HTML_VALUE);
            switch (statusCode == null ? 0 : statusCode) {
                case HttpStatus.SC_NOT_FOUND:
                    response.setStatus(HttpStatus.SC_NOT_FOUND);
                    response.getWriter().println("没有你想要的东西!");
                    break;
                case HttpStatus.SC_INTERNAL_SERVER_ERROR:
                    response.setStatus(HttpStatus.SC_NOT_FOUND);
                    response.getWriter().println("系统在运行中出现了毛病!");
                    break;
                default:
                    response.setStatus(HttpStatus.SC_NOT_FOUND);
                    response.getWriter().println("我也不知道出现了什么状况!");
            }
        }catch (IOException e){
            log.error("", e);
        }
    }

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

这样可以捕捉到包括400在内的各种异常。

更新:ErrorController使用errorAttribute能更好的获取错误信息

@Autowired
    private ErrorAttributes errorAttributes;

    private Map<String, Object> getErrorAttributes(HttpServletRequest request,
                                                   boolean includeStackTrace) {
        ServletWebRequest servletWebRequest = new ServletWebRequest(request);
        return this.errorAttributes.getErrorAttributes(servletWebRequest,
                includeStackTrace);
    }

使用:

Map error = getErrorAttributes(request, true);
Integer statusCode = (Integer)error.get("status");
        String path = (String) error.get("path");
        String message = (String) error.get("message");

相关文章

网友评论

      本文标题:Spring boot 配置错误捕获

      本文链接:https://www.haomeiwen.com/subject/fmpubctx.html