Spring Boot - 异常处理

1.默认异常处理

Spring Boot对Web应用提供了默认的异常处理

访问不存在的url,会得到如下错误页面

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.
Tue Sep 26 16:19:33 CST 2017
There was an unexpected error (type=Not Found, status=404).
No message available

或者代码出现异常

    @RequestMapping("/test")
    public String test() throws Exception {
        throw new Exception("there's an error");
    }

得到类似的错误页面

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.
Tue Sep 26 16:19:33 CST 2017
There was an unexpected error (type=Not Found, status=404).
No message available

这些是Spring Boot提供的默认的错误页面,无需任何配置,但相对比较粗陋,展现给用户不够友好,我们可以自定义错误页面、自定义错误提示。

2.自定义异常处理

2.1 直接返回错误页面(html)

Step 1:在SpringbootApplication.java同级目录下创建ExceptionHelper.java

@ControllerAdvice定义统一的异常处理类
@ExceptionHandler针对异常类型映射相应的错误页面

package com.example.springboot;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
@SuppressWarnings("unused")
public class ExceptionHelper {

    @ExceptionHandler(value = Exception.class)
    public ModelAndView error(HttpServletRequest httpServletRequest,Exception e){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("exception",e);
        modelAndView.addObject("url",httpServletRequest.getRequestURL());
        modelAndView.setViewName("error");
        return modelAndView;
    }
}

Step 2:自定义错误页面./templates/error.html(使用了thymeleaf模板引擎)

<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head lang="en">
    <meta charset="UTF-8" />
    <title>异常处理</title>
</head>
<body>
<div th:text="${url}"></div>
<div th:text="${exception.message}"></div>
</body>
</html>

Step 3:访问异常后得到自定义的错误页面(这个错误页面比较简单,可以根据实际需要制作精美的错误页面)

http://localhost:8080/test
there's an error
2.2 返回json格式错误信息

在后端只提供API的场景下,前端调用者往往需要的不是错误页面,而是错误数据(通常是json类型)。此时
仅需要修改ExceptionHelper.java,给@ExceptionHandler相应的方法加上@ResponseBody就能返回json格式的结果了。

package com.example.springboot;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
@SuppressWarnings("unused")
public class ExceptionHelper {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public String error(HttpServletRequest httpServletRequest,Exception e){
        return String.format("{\"url\":\"%s\",\"error\":\"%s\"}",httpServletRequest.getRequestURL(),e.getLocalizedMessage());
    }
}

返回结果如下:

{"url":"http://localhost:8080/test","error":"there's an error"}

上面的示例中仅处理了Exception,实际开发中可以根据不同的异常分别处理,这样体验会比较好。

    原文作者:yuanzicheng
    原文地址: https://www.jianshu.com/p/1f42a33a6a85
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞