栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【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";
    }

    
    @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中可以自定义返回内容,例如:



    
    Title


404静态错误


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 依赖如下;

    org.springframework.boot
    spring-boot-autoconfigure
    1.5.15.RELEASE

  • 依赖无法导入或其他问题建议降低spring-boot-starter-parent版本。
2.5 参考
  • SpringBoot实战(03):全局异常处理ErrorController
  • 关于springboot 从controller返回到html页面
  • 关于springboot 从controller指定跳转到html页面
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/862171.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号