Spring Boot 全局异常处理

2018-10-23  本文已影响33人  小昭文

完善的异常处理可以让客户端有一个良好的体验,并且有利于定位出错原因,帮助解决问题。
Spring Boot 内置了一个 /error 处理,当抛出异常之后,会被转到这个映射进行处理, 就是常见的 Whitelable Error Page

image.png

但是这个界面长相难看,不够友好,需要我们做一些工作。

一、传统项目中的错误页面

项目中发生异常之后,最好能给予一些必要的提示,在开发阶段甚至可以打印出完整的堆栈信息,以快速定位解决问题。

1)创建一个错误界面error.html,用于展示错误内容

在resources>templates文件夹下,新建一个error.html的模板文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Spring Boot 错误处理</title>
</head>
<body>
    <h1>错误处理</h1>
    <h3 th:text="'错误信息:'+${msg}"></h3>
    <h3 th:text="'请求地址:'+${url}"></h3>
    <h2>异常堆栈跟踪日志StackTrace</h2>
    <div th:each="line:${stackTrace}">
        <div th:text="${line}"></div>
    </div>
</body>
</html>

2)创建一个全局处理类。使用 @ControllerAdvice@ExceptionHandler注解来处理错误信息

新建一个exception的包,然后在此包下新建一个PageExceptionHandler的类

/**
 * 传统系统中的有错误界面
 *
 * @author xiaozhao
 * @date 2018/10/23下午1:59
 */
@ControllerAdvice
public class PageExceptionHandler {


    /**
     * 返回到错误页面,位于resources>templates>error.html文件
     *
     * @param req
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = Exception.class)
    public ModelAndView pageExceptionHandle(HttpServletRequest req, Exception e) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("msg", e.getMessage());
        modelAndView.addObject("url", req.getRequestURL());
        // 模板名称
        modelAndView.setViewName("error");
        return modelAndView;
    }
}

现在使用一个控制器来测试一下,在控制器的代码中抛出异常,例如:

/**
     * 传统项目中的界面
     *
     * @return
     * @throws Exception
     */
    @GetMapping("/page")
    public String page() throws Exception {
        throw new Exception("发生了界面错误");
    }

运行之后,发出存在错误的请求,显示如下的界面

image.png

二、rest类型的错误展示

这种场景下是不需要error.html的,只需要修改下@ControllerAdvice修饰的类即可,修改方法的返回值,然后添加@ResponseBody的注解

或者直接把@ControllerAdvice修改为@RestControllerAdvice即可,下面的方法中不再需要@ResponseBody注解

@RestControllerAdvice
public class RestExceptionHandler {
  @ExceptionHandler(value = Exception.class)
    public HttpResult<String> restExceptionHandle(Exception e) {
        //......
    }
}

或者

@ControllerAdvice
public class RestExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public HttpResult<String> restExceptionHandle(Exception e) {
        //......
    }
}

这里使用第一种方式

/**
 * 处理类似rest风格的接口,返回json
 *
 * @author xiaozhao
 * @date 2018/10/23下午1:32
 */
@RestControllerAdvice
public class RestExceptionHandler {
    private final Logger logger = LoggerFactory.getLogger(RestExceptionHandler.class);

    /**
     * 返回json
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public HttpResult<String> restExceptionHandle(Exception e) {
        logger.error(e.getMessage());
        HttpResult<String> result = new HttpResult<>();
        result.setCode(-1);
        result.setMsg(e.getMessage());
        return result;
    }
}

其中的HttpResult是一个包装类,统一返回格式

/**
 * http请求返回的最外层对象
 *
 * @author xiaozhao
 * @date 2018/10/23下午1:34
 */
public class HttpResult<T> {
    /**
     * 错误码
     */
    private Integer code;

    /**
     * 提示信息
     */
    private String msg;

    /**
     * 具体的内容
     */
    private T data;

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "HttpResult{" +
                "code=" + code +
                ", msg='" + msg + '\'' +
                ", data=" + data +
                '}';
    }
}

控制器调用代码

/**
     * rest服务,返回json数据
     *
     * @return
     * @throws RestException
     */
    @GetMapping("/rest")
    @ResponseBody
    public String hello() throws RestException {
        throw new RestException("发生自定义rest错误");
    }

运行后的结果


image.png

三、统一2种显示

一般项目中可能会同时存在2种形式,上面2种形式差别就是返回值的不同,可以统一起来,都返回Object类型,然后内部根据请求头的信息,判断是那种类型的请求。

当判断请求为jons格式时,使用HttpResult进行返回,当请求为界面时,返回ModelAndView

完整代码如下:

**
 * 处理项目中的异常,既包含传统项目中的界面,也包含了rest形式的json返回
 *
 * @author xiaozhao
 * @date 2018/10/23下午3:12
 */
@RestControllerAdvice
public class GlobalExceptionHandler2 {
    private final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler2.class);

    @ExceptionHandler(Exception.class)
    public Object defaultExceptionHandle(Exception e, HttpServletRequest request) {
        boolean isAjax = isAjax(request);
        if (isAjax) {
            logger.error("Ajax 请求异常" + e.getMessage());
            HttpResult<String> result = new HttpResult<>();
            result.setCode(-1);
            result.setMsg(e.getMessage());
            return result;
        } else {
            logger.error("界面请求异常" + e.getMessage());
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.addObject("msg", e.getMessage());
            modelAndView.addObject("url", request.getRequestURL());
            modelAndView.addObject("stackTrace", e.getStackTrace());
            modelAndView.setViewName("error");
            return modelAndView;
        }
    }

    /**
     * 判断网络请求是否为ajax
     *
     * @param req
     * @return
     */
    private boolean isAjax(HttpServletRequest req) {
        String contentTypeHeader = req.getHeader("Content-Type");
        String acceptHeader = req.getHeader("Accept");
        String xRequestedWith = req.getHeader("X-Requested-With");
        return (contentTypeHeader != null && contentTypeHeader.contains("application/json"))
                || (acceptHeader != null && acceptHeader.contains("application/json"))
                || "XMLHttpRequest".equalsIgnoreCase(xRequestedWith);
    }
}

最终代码

https://github.com/xiaozhaowen/spring-boot-in-action/tree/master/springboot-handle-exception

上一篇 下一篇

猜你喜欢

热点阅读