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应用程序。

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

相关文章

  • Spring自定义注解的实现与使用方式

    Spring自定义注解的实现与使用方式

    注解是Java中用于类、方法、参数、包的装饰标志,本身不具备功能,但可定义参数,Java包含内建注解和元注解,如@Target、@Retention等,描述注解的使用范围和生命周期,Spring的AOP(面向切面编程)可以结合注解实现功能,如权限控制和日志记录
    2024-09-09
  • 基于Java HashMap的死循环的启示详解

    基于Java HashMap的死循环的启示详解

    本篇文章是对Java HashMap的死循环进行了详细的分析介绍,需要的朋友参考下
    2013-05-05
  • 浅谈springboot与微服务架构

    浅谈springboot与微服务架构

    这篇文章主要介绍了浅谈springboot与微服务架构,SpringBoot是由 Pivotal团队提供的框架,其设计⽬的是⽤来简化新Spring应⽤,初始搭建以及开发过程,该框架使⽤了特定的⽅式来进⾏配置,需要的朋友可以参考下
    2023-07-07
  • Java生成范围内随机整数的三种方法

    Java生成范围内随机整数的三种方法

    在Java中生成随机数的场景有很多,下面这篇文章主要给大家介绍了关于Java生成范围内随机整数的三种方法,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2022-07-07
  • Quarkus的Spring扩展快速改造Spring项目

    Quarkus的Spring扩展快速改造Spring项目

    这篇文章主要为大家介绍了Quarkus的Spring项目扩展,带大家快速改造Spring项目示例演绎,有需要的朋友可以借鉴参考下,希望能够有所帮助
    2022-02-02
  • SpringBoot应用中PDF添加水印的五种实现方案对比

    SpringBoot应用中PDF添加水印的五种实现方案对比

    在 Spring Boot 应用中实现 PDF 添加水印,这篇文章为大家整理了五种常见方案及详细实现步骤,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
    2025-08-08
  • springboot集成微软teams的实例代码

    springboot集成微软teams的实例代码

    Microsoft Teams 是一款基于聊天的智能团队协作工具,可以同步进行文档共享,并为成员提供包括语音、视频会议在内的即时通讯工具,今天给大家介绍springboot集成微软teams的示例代码,感兴趣的朋友一起看看吧
    2022-01-01
  • Java实现PDF导出功能的示例代码

    Java实现PDF导出功能的示例代码

    这篇文章主要为大家详细介绍了Java实现PDF导出功能的相关知识,文中的示例代码讲解详细,具有一定的学习价值,感兴趣的小伙伴可以了解下
    2023-09-09
  • intellij idea 将模块打jar包的步骤详解

    intellij idea 将模块打jar包的步骤详解

    这篇文章主要介绍了intellij idea 将模块打jar包的步骤,本文图文并茂给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2018-09-09
  • Java接口幂等性设计原理解析

    Java接口幂等性设计原理解析

    这篇文章主要介绍了Java接口幂等性设计原理解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-05-05

最新评论