java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot全局异常拦截与自定义错误页面

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

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

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

您可能感兴趣的文章:
阅读全文