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

 更新时间:2025年12月12日 14:29:24   作者:fanxbl957  
本文介绍了SpringBoot中全局异常拦截与自定义错误页面的实现方法,包括异常的分类、SpringBoot默认异常处理机制、全局异常拦截实现、自定义错误页面实现以及两者的结合使用,通过这些技术,可以提高系统的稳定性和用户体验

一、引言

在开发基于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应用程序。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • SpringBoot整合Mybatis与thymleft实现增删改查功能详解

    SpringBoot整合Mybatis与thymleft实现增删改查功能详解

    MybatisPlus是国产的第三方插件, 它封装了许多常用的CURDapi,免去了我们写mapper.xml的重复劳动。本文将整合MybatisPlus实现增删改查功能,感兴趣的可以了解一下
    2022-12-12
  • Java中stream的用法详细解读

    Java中stream的用法详细解读

    这篇文章主要介绍了Java中stream的用法详细解读,Stream 是 Java8 中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作,使用Stream API 对集合数据进行操作,就类似于使用SQL执行的数据库查询,需要的朋友可以参考下
    2023-10-10
  • spring cloud gateway跨域全局CORS配置方式

    spring cloud gateway跨域全局CORS配置方式

    这篇文章主要介绍了spring cloud gateway跨域全局CORS配置方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-07-07
  • Java spring webmvc如何实现控制反转

    Java spring webmvc如何实现控制反转

    这篇文章主要介绍了Java spring webmvc如何实现控制反转,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-08-08
  • Java中的CAS和ABA问题说明

    Java中的CAS和ABA问题说明

    这篇文章主要介绍了Java中的CAS和ABA问题说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-05-05
  • 轻量级声明式的Http库——Feign的独立使用

    轻量级声明式的Http库——Feign的独立使用

    这篇文章主要介绍了轻量级声明式的Http库——Feign的使用教程,帮助大家更好的理解和学习使用feign,感兴趣的朋友可以了解下
    2021-04-04
  • Spring Boot2.3 新特性分层JAR的使用

    Spring Boot2.3 新特性分层JAR的使用

    这篇文章主要介绍了Spring Boot2.3 新特性分层JAR的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-06-06
  • Springboot配置文件相关说明解析

    Springboot配置文件相关说明解析

    这篇文章主要介绍了Springboot配置文件相关说明解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-06-06
  • mybatis+springboot发布postgresql数据的实现

    mybatis+springboot发布postgresql数据的实现

    本文主要介绍了mybatis+springboot发布postgresql数据的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-11-11
  • mybatis插入一条数据返回相应数据ID问题及解决

    mybatis插入一条数据返回相应数据ID问题及解决

    MyBatis插入数据并获取自增ID的方法,通过设置useGeneratedKeys=true和keyProperty属性,可以自动将生成的ID赋值给实体对象的相应属性
    2026-05-05

最新评论