高级java每日一道面试题-2025年01月28日-框架篇[SpringBoot篇]-如何使用Spring Boot实现异常处理?

如果有遗漏,评论区告诉我进行补充

面试官: 如何使用Spring Boot实现异常处理?

我回答:

在 Java 高级面试中讨论如何使用 Spring Boot 实现异常处理时,我们可以从多个角度进行详细阐述。这包括全局异常处理、特定异常处理、使用 @ResponseStatus 注解、自定义异常类、异常处理与日志记录、异常处理与前端交互的最佳实践等。以下是对这些方面的综合介绍:

一、Spring Boot 异常处理概述

Spring Boot 提供了多种方式来处理异常,确保开发者能够灵活地捕获和处理应用程序中的各种异常。这不仅有助于提供用户友好的错误响应,还能进行必要的日志记录以便后续分析。

二、全局异常处理

使用 @ControllerAdvice@ExceptionHandler
  • 创建一个类并使用 @ControllerAdvice 注解:这个类会被 Spring 识别为全局异常处理类。
  • 在该类中使用 @ExceptionHandler 注解:标记处理特定异常的方法。

示例代码:

java">import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseEntity<String> handleAllExceptions(Exception e) {
        // 这里可以记录日志、返回错误信息给前端等
        return new ResponseEntity<>("An unexpected error occurred: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }

    // 可以添加更多的 @ExceptionHandler 方法来处理特定的异常类型
}

三、特定异常处理

除了全局异常处理外,Spring Boot 还允许在控制器中处理特定的异常。通过在控制器方法中使用 @ExceptionHandler 注解,可以针对特定类型的异常进行处理。

示例代码:

java">import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @GetMapping("/test")
    public String test() throws CustomException {
        throw new CustomException("This is a custom exception.");
    }

    @ExceptionHandler(CustomException.class)
    public ResponseEntity<String> handleCustomException(CustomException ex) {
        return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST);
    }
}

四、使用 @ResponseStatus 注解

对于某些特定的异常,可以直接在异常类上使用 @ResponseStatus 注解来指定当该异常被抛出时应该返回的 HTTP 状态码。

示例代码:

java">import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
    public ResourceNotFoundException(String message) {
        super(message);
    }
}

五、自定义异常类

为了更好地组织和管理异常,开发者可以创建自定义的异常类,并在这些类中使用 @ResponseStatus 注解或让它们继承自带有 @ResponseStatus 注解的异常类。

示例代码:

java">public class CustomException extends RuntimeException {

    public CustomException(String message) {
        super(message);
    }

    public CustomException(String message, Throwable cause) {
        super(message, cause);
    }
}

六、异常处理与日志记录

在处理异常时,通常还需要记录日志以便后续分析和调试。Spring Boot 可以与各种日志框架(如 Logback、Log4j 等)集成,开发者可以在异常处理方法中使用这些日志框架来记录异常信息。

示例代码:

java">import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<String> handleAllExceptions(Exception e) {
        logger.error("Unexpected error occurred", e);
        return new ResponseEntity<>("An unexpected error occurred: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

七、异常处理与前端交互

在 Web 应用程序中,异常处理还需要考虑与前端的交互。通常,开发者会设计一套统一的错误响应格式,并在异常处理方法中返回这种格式的响应。这样,前端就可以根据响应中的错误代码或消息来显示相应的错误提示。

示例代码:

java">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(value = Exception.class)
    public ResponseEntity<ErrorResponse> handleAllExceptions(Exception e) {
        ErrorResponse errorResponse = new ErrorResponse("ERROR", e.getMessage());
        return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

class ErrorResponse {
    private String status;
    private String message;

    public ErrorResponse(String status, String message) {
        this.status = status;
        this.message = message;
    }

    // Getters and Setters
}

八、最佳实践

  1. 不要捕获并吞掉异常:捕获异常后应该进行适当的处理(如记录日志、返回错误信息给前端等),而不是简单地吞掉异常。
  2. 区分业务异常和技术异常:业务异常应该由业务层抛出并由控制器层捕获处理;技术异常(如数据库连接异常、网络异常等)则应该在全局异常处理类中统一处理。
  3. 提供有用的错误信息:返回给前端的错误信息应该是有意义的,能够帮助前端开发者或用户定位问题。
  4. 使用统一的错误响应格式:这有助于前端开发者更方便地处理错误响应。

总结

在 Spring Boot 中实现异常处理需要综合运用多种机制和技巧,包括全局异常处理、特定异常处理、使用 @ResponseStatus 注解、自定义异常类以及异常处理与日志记录和前端交互的最佳实践。理解这些机制及其应用场景,有助于构建健壮的应用程序,并在面试中展示出对 Spring Boot 框架深入的理解和实际项目经验。


http://www.niftyadmin.cn/n/5843011.html

相关文章

GitHub Copilot 越狱漏洞

研究人员发现了两种操控 GitHub 的人工智能&#xff08;AI&#xff09;编码助手 Copilot 的新方法&#xff0c;这使得人们能够绕过安全限制和订阅费用、训练恶意模型等。 第一种技巧是将聊天交互嵌入 Copilot 代码中&#xff0c;利用 AI 的问答能力&#xff0c;使其产生恶意输…

PyQt6/PySide6 的 QTreeView 类

QTreeView 是 PyQt6 或 PySide6 库中用于显示分层数据的控件。它适用于展示树形结构的数据&#xff0c;如文件系统、组织结构等。QTreeView 也是基于模型-视图架构的&#xff0c;通常与 QAbstractItemModel 的子类&#xff08;如 QStandardItemModel 或自定义模型&#xff09;一…

最新EFK(Elasticsearch+FileBeat+Kibana)日志收集

文章目录 1.EFK介绍2.操作前提3.FileBeat8.15下载&安装4.编写FileBeat配置文件5.启动FileBeat6.模拟实时日志数据生成7.查看索引(数据流)是否创建成功8.创建数据视图&#xff1a;9.查看数据视图10.使用KQL对采集的日志内容进行过滤11.给日志数据配置保留天数(扩展知识) 1.E…

【力扣】48.旋转图像

AC截图 题目 思路 以矩阵 1 2 3 4 5 6 7 8 9 为例&#xff0c;想要翻转90度&#xff0c;可以先沿着对角线翻转一次 1 4 7 2 5 8 3 6 9 然后再逐行翻转&#xff0c;即可得到所求矩阵 7 4 1 8 5 2 9 6 3 代码 class Solution { public:void rotate(vector<vector…

亚远景-从SPICE到ASPICE:汽车软件开发的标准化演进

一、SPICE标准的起源与背景 SPICE&#xff0c;全称“Software Process Improvement and Capability dEtermination”&#xff0c;即“软件流程改进和能力测定”&#xff0c;是由国际标准化组织ISO、国际电工委员会IEC、信息技术委员会JTC1联合发起制定的ISO 15504标准。该标准旨…

git 指定ssh key

在git clone操作中指定SSH密钥&#xff0c;可以通过以下几种方法实现&#xff1a; 1 使用–config选项在克隆时指定密钥 当你克隆一个git仓库时&#xff0c;可以直接在命令中指定要使用的ssh密钥。这种方法适用于一次性操作&#xff0c;不需要修改全局或仓库级别的配置 git …

libdrm移植到arm设备

一、环境资源要求 下载libdrm Index of /libdrm 这边使用的是2.4.114版本&#xff0c;版本太高对meson版本要求也很高&#xff0c;为了省事用apt安装meson就不用太高版本了&#xff0c;1.x版本虽然使用makefile编译方便但是太老&#xff0c;对应用支持不太好。 https://dri…

【Kubernetes Pod间通信-第3篇】Kubernetes中Pod与ClusterIP服务之间的通信

引言 我们之前了解了在不同场景下,Kubernetes中Pod之间的通信是如何路由的。 【Kubernetes Pod间通信-第1篇】在单个子网中使用underlay网络实现Pod到Pod的通信【Kubernetes Pod间通信-第2篇】使用BGP实现Pod到Pod的通信现在,我们来看看在集群中,Pod与服务之间的通信是如何…