当前位置: 代码网 > it编程>编程语言>Java > SpringBoot全局异常拦截与自定义错误页面实现过程解读

SpringBoot全局异常拦截与自定义错误页面实现过程解读

2025年12月12日 Java 我要评论
一、引言在开发基于spring boot的应用程序时,异常处理是一个至关重要的环节。合理的异常处理机制不仅可以提高系统的稳定性和可靠性,还能为用户提供友好的错误反馈。本文将深入探讨spring boo

一、引言

在开发基于spring boot的应用程序时,异常处理是一个至关重要的环节。合理的异常处理机制不仅可以提高系统的稳定性和可靠性,还能为用户提供友好的错误反馈。

本文将深入探讨spring boot中全局异常拦截与自定义错误页面的实现,旨在帮助技术人员掌握这一关键技能。

二、spring boot异常处理基础

2.1 异常的分类

在java中,异常分为受检查异常(checked exception)和非受检查异常(unchecked exception)。

受检查异常通常是程序在编译时就需要处理的异常,如ioexception;非受检查异常一般是运行时异常,如nullpointerexception、arrayindexoutofboundsexception等。

2.2 spring boot默认异常处理机制

spring boot为我们提供了默认的异常处理机制。当应用程序抛出异常时,spring boot会根据异常类型返回相应的http状态码和错误信息。例如,当发生404错误时,会返回一个包含错误信息的json响应。

下面是一个简单的spring boot应用示例:

import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;
import org.springframework.web.bind.annotation.getmapping;
import org.springframework.web.bind.annotation.restcontroller;

@springbootapplication
@restcontroller
public class demoapplication {

    public static void main(string[] args) {
        springapplication.run(demoapplication.class, args);
    }

    @getmapping("/test")
    public string test() {
        throw new runtimeexception("test exception");
    }
}

当访问/test路径时,spring boot会返回一个包含错误信息的json响应。

三、全局异常拦截实现

3.1 自定义异常处理器

为了实现全局异常拦截,我们可以创建一个自定义的异常处理器类,使用@controlleradvice@exceptionhandler注解。@controlleradvice注解用于定义全局异常处理器,@exceptionhandler注解用于指定处理的异常类型。

以下是一个简单的全局异常处理器示例:

import org.springframework.http.httpstatus;
import org.springframework.http.responseentity;
import org.springframework.web.bind.annotation.controlleradvice;
import org.springframework.web.bind.annotation.exceptionhandler;

@controlleradvice
public class globalexceptionhandler {

    @exceptionhandler(runtimeexception.class)
    public responseentity<string> handleruntimeexception(runtimeexception e) {
        return new responseentity<>("runtime exception occurred: " + e.getmessage(), httpstatus.internal_server_error);
    }
}

在上述代码中,globalexceptionhandler类使用@controlleradvice注解标记为全局异常处理器,handleruntimeexception方法使用@exceptionhandler注解指定处理runtimeexception类型的异常。

3.2 处理不同类型的异常

除了处理runtimeexception,我们还可以处理其他类型的异常。

例如,处理nullpointerexceptionillegalargumentexception

import org.springframework.http.httpstatus;
import org.springframework.http.responseentity;
import org.springframework.web.bind.annotation.controlleradvice;
import org.springframework.web.bind.annotation.exceptionhandler;

@controlleradvice
public class globalexceptionhandler {

    @exceptionhandler(nullpointerexception.class)
    public responseentity<string> handlenullpointerexception(nullpointerexception e) {
        return new responseentity<>("null pointer exception occurred: " + e.getmessage(), httpstatus.internal_server_error);
    }

    @exceptionhandler(illegalargumentexception.class)
    public responseentity<string> handleillegalargumentexception(illegalargumentexception e) {
        return new responseentity<>("illegal argument exception occurred: " + e.getmessage(), httpstatus.bad_request);
    }
}

3.3 自定义异常类

在实际开发中,我们可以创建自定义异常类,以便更好地管理和处理特定业务场景下的异常。

例如,创建一个自定义的业务异常类:

public class businessexception extends runtimeexception {
    public businessexception(string message) {
        super(message);
    }
}

然后在全局异常处理器中处理该自定义异常:

import org.springframework.http.httpstatus;
import org.springframework.http.responseentity;
import org.springframework.web.bind.annotation.controlleradvice;
import org.springframework.web.bind.annotation.exceptionhandler;

@controlleradvice
public class globalexceptionhandler {

    @exceptionhandler(businessexception.class)
    public responseentity<string> handlebusinessexception(businessexception e) {
        return new responseentity<>("business exception occurred: " + e.getmessage(), httpstatus.bad_request);
    }
}

四、自定义错误页面实现

4.1 基本原理

spring boot允许我们自定义错误页面,当发生特定的http状态码错误时,会自动跳转到相应的错误页面。

我们可以在src/main/resources/templates目录下创建错误页面文件,文件名格式为error-{status}.html,其中{status}为http状态码。

4.2 创建自定义错误页面

以下是一个简单的404错误页面示例(error-404.html):

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>404 not found</title>
</head>
<body>
    <h1>404 not found</h1>
    <p>the requested resource was not found.</p>
</body>
</html>

同样,我们可以创建500错误页面(error-500.html):

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>500 internal server error</title>
</head>
<body>
    <h1>500 internal server error</h1>
    <p>an unexpected error occurred on the server.</p>
</body>
</html>

4.3 配置错误页面

在spring boot中,默认情况下会自动查找src/main/resources/templates目录下的错误页面。如果需要自定义错误页面的位置,可以在application.propertiesapplication.yml中进行配置。

application.properties中配置:

server.error.path=/error
spring.mvc.view.prefix=/templates/
spring.mvc.view.suffix=.html

application.yml中配置:

server:
  error:
    path: /error
spring:
  mvc:
    view:
      prefix: /templates/
      suffix: .html

五、集成全局异常拦截与自定义错误页面

5.1 异常处理与错误页面结合

在全局异常处理器中,我们可以根据异常类型返回不同的http状态码,从而跳转到相应的错误页面。例如:

import org.springframework.http.httpstatus;
import org.springframework.http.responseentity;
import org.springframework.web.bind.annotation.controlleradvice;
import org.springframework.web.bind.annotation.exceptionhandler;

@controlleradvice
public class globalexceptionhandler {

    @exceptionhandler(runtimeexception.class)
    public responseentity<void> handleruntimeexception(runtimeexception e) {
        return new responseentity<>(httpstatus.internal_server_error);
    }

    @exceptionhandler(illegalargumentexception.class)
    public responseentity<void> handleillegalargumentexception(illegalargumentexception e) {
        return new responseentity<>(httpstatus.bad_request);
    }
}

当发生runtimeexception时,会返回500状态码,跳转到error-500.html页面;当发生illegalargumentexception时,会返回400状态码,跳转到error-400.html页面。

5.2 测试与验证

启动spring boot应用程序,访问不同的路径,触发不同类型的异常,验证全局异常拦截和自定义错误页面是否正常工作。

六、总结

通过本文的介绍,我们了解了spring boot中全局异常拦截与自定义错误页面的实现方法。

全局异常拦截可以帮助我们统一处理应用程序中的异常,提高代码的可维护性和系统的稳定性;自定义错误页面可以为用户提供更友好的错误反馈,提升用户体验。

在实际开发中,我们可以根据具体需求灵活运用这些技术,打造更加健壮和易用的spring boot应用程序。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com