【SpringBoot】实现自定义异常处理

【SpringBoot】实现自定义异常处理

1. 背景

    当用户输入的url不合法时,页面会给出以下提示;
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing
this as a fallback.
Tue Nov 29 10:48:26 CST 2016 There was an unexpected error (type=Bad
Request, status=400). Required String parameter ‘fileName’ is not
present
    显然以上提示对用户不友好,因此需要根据不同的错误类型,自定义为用户返回更加友好的提示。

2. 具体实现

2.1 BasicErrorController

    新建BasicErrorController 继承 ErrorController(org.springframework.boot.autoconfigure.web) 实现getErrorPath()方法; 编写handleError()方法处理不同的状态码; BasicErrorController.java 如下。
@Controller
public class BasicErrorController implements ErrorController {
          
   

    @Override
    public String getErrorPath() {
          
   
        return "/error";
    }

    /**
     * request error handler.
     * @param request request
     * @return model name
     */
    @RequestMapping("/error")
    public String handleError(HttpServletRequest request) {
          
   
        Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        if (status != null) {
          
   
            Integer statusCode = Integer.valueOf(status.toString());

            if (statusCode == HttpStatus.NOT_FOUND.value()) {
          
   
                return "/404.html";
            } else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
          
   
                return "/500.html";
            } else if (statusCode == HttpStatus.BAD_REQUEST.value()) {
          
   
                return "/400.html";
            }
        }
        return "/error.html";
    }

}

2.2 静态文件

    静态文件存放位置为 src/main/resources/static; 具体如下图所示; 在404.html中可以自定义返回内容,例如:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
404静态错误
</body>
</html>

2.3 测试

    新建TestController,增加合法接口/now;
@Controller
public class TestController {
          
   

    @RequestMapping("/now")
    @ResponseBody
    public String now(){
          
   
        return "2022-05-06";
    }
}
    访问/now接口; 其他非法接口,如/test; 至此实现了根据错误类型自定义返回页面;

2.4 注意点

    ErrorController 是 org.springframework.boot.autoconfigure.web 下的接口;
package org.springframework.boot.autoconfigure.web;

public interface ErrorController {
          
   
    String getErrorPath();
}
    spring-boot-autoconfigure 依赖如下;
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-autoconfigure</artifactId>
    <version>1.5.15.RELEASE</version>
</dependency>
    依赖无法导入或其他问题建议降低spring-boot-starter-parent版本。

2.5 参考

经验分享 程序员 微信小程序 职场和发展