0
点赞
收藏
分享

微信扫一扫

SpringBoot统一异常处理之404、500系统异常处理

路西法阁下 2022-03-16 阅读 125

之前的一篇文章里面写到的SpringBoot的统一异常处理类,处理异常很是方便,但是其中内容缺少了一部分,也就是404或者500系统异常的处理,因为这些异常是没有进入到接口内部,处理方式和普通的异常处理会有区别。

统一异常处理

处理代码如下:

@ControllerAdvice
public class ExceptionHandler {

    @Bean
    public WebServerFactoryCustomizer<ConfigurableWebServerFactory> factoryCustomizer() {
        return factory -> {
            // 出现404跳转到404页面
            ErrorPage notFound = new ErrorPage(HttpStatus.NOT_FOUND, "/404");
            // 出现500跳转到500页面
            ErrorPage sysError = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500");
            factory.addErrorPages(notFound,sysError);
        };
    }
}

代码很简单,没什么说的,但是这里需要注意的是WebServerFactoryCustomizer在SpringBoot 1.x版本是没有的,必须将SpringBoot升级到2.x版本。另外一个需要注意的点是在指定地址的时候必须在前面加上’/’,如上面的404,必须在404前加上’/’,否则在启动的时候就会报错。

控制层跳转

@Controller
@RequestMapping("/")
public class PageController {

    @RequestMapping("index")
    public String index(){
        return "index";
    }

    // 404跳转
    @RequestMapping("404")
    public String notFound(){
        return "404";
    }

    // 500跳转
    @RequestMapping("500")
    public String sysError(){
        return "500";
    }
}

在统一异常处理类里面指定404和500跳转的地址,就需要在控制层指定具体返回的页面。

需要引入的依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

这里SpringBoot使用的是2.0.2.RELEASE版本,通过parent标签引入如下:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.2.RELEASE</version>
</parent>
举报

相关推荐

0 条评论