为所有资源实现通用异常处理

17 Jan 2025 | 3 分钟阅读

正如我们之前讨论的那样,我们应该定义一个标准异常结构,该结构在所有 RESTful 服务中遵循。在本节中,我们将讨论为所有资源实现通用异常处理

让我们看看如何自定义异常消息。

步骤 1:创建一个名为 com.javatpoint.server.main.exception 的新包。

步骤 2:在上面的包中创建一个名为 ExceptionResponse 的类。

步骤 3:在基本层面,异常结构有三个关键要素:时间戳、消息详细信息。定义这三个字段。

步骤 4:使用字段生成构造函数。

步骤 5:生成 Getter,不需要 Setter。

一旦定义了结构,我们就可以定义它的 Java 实现。每当发生异常时,我们将以特定格式返回响应。该结构是最重要的部分,并且必须与语言无关。

Spring Framework 中一个重要的类是 ResponseEntityExceptionHandler 类。它是一个抽象的基类,用于提供跨所有不同异常处理程序方法的集中式异常处理。我们将扩展此类以处理和提供自定义的异常处理功能。此异常处理功能应用于所有控制器,如 HellowWorldController、UserResource(Controller)。

步骤 6:在包 com.javatpoint.server.main.exception 中创建一个名为 CustomizedResponseEntityExceptionHandler 的新类,并扩展 ResponseEntityExceptionHandler 类。

步骤 7:添加 @ControllerAdvice 和 @RestController 注解。

步骤 8:在包资源管理器中展开 Maven Dependencies -> 展开 spring-webmvc-5.1.9.RELEASE.jar -> 展开 org.springframework.web.servlet.mvc.method.annotation -> 打开 ResponseEntityExceptionHandler.class

Implementing Generic Exception Handling for all Resources

步骤 9:从 ResponseEntityExceptionHandler.class 复制 ResponseEntityMethod<Object> 方法并粘贴到 CustomizedResponseEntityExceptionHandler.java 文件中。

步骤 10:覆盖 ResponseEntityMethod 方法。将方法名称重命名为 handleAllExceptions()。

步骤 11:创建异常响应结构。

步骤 12:创建一个 ResponseEntity 对象,并将异常响应和 Http 状态作为参数传递。

CustomizedResponseEntityExceptionHandler.java

步骤 13:打开 rest 客户端 Postman 并发送一个 Get 请求。我们得到 状态:500 Internal Server Error 和我们定义的异常结构。

Implementing Generic Exception Handling for all Resources

如果我们要将状态Internal Server Error 自定义为 Not Found,则需要在 CustomizedResponseEntityExceptionHandler.java 文件中更改一些内容。

CustomizedResponseEntityExceptionHandler.java

再次移动到 Postman 并发送一个 Get 请求。我们得到 状态:404 Not Found 以及定义的异常结构。

Implementing Generic Exception Handling for all Resources