如何使用Spring Boot实现异常处理?
1 个回答
看透不说透,是规矩,也是格局。商正梁在 Spring Boot 中,异常处理可以通过 `@ControllerAdvice` 注解来实现,这是一个非常有用的方法,可以集中处理控制器类抛出的所有异常。下面是重新整理后的内容: ### 使用 Spring Boot 实现异常处理 **概述**: Spring 提供了一种通过 `@ControllerAdvice` 注解来集中处理控制器类抛出的异常的方法。这种方式可以使异常处理逻辑集中管理,保持代码的整洁和可维护性。 **实现步骤**: 1. **创建一个异常处理类**: 使用 `@ControllerAdvice` 注解创建一个类,这个类将用于处理全局异常。 ```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.context.request.WebRequest; @ControllerAdvice public class GlobalExceptionHandler { // 处理特定异常 @ExceptionHandler(ResourceNotFoundException.class) public ResponseEntity<?> handleResourceNotFoundException(ResourceNotFoundException ex, WebRequest request) { ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(false)); return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND); } // 处理全局异常 @ExceptionHandler(Exception.class) public ResponseEntity<?> handleGlobalException(Exception ex, WebRequest request) { ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(false)); return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR); } } ``` 2. **定义错误详情类**: 创建一个类来表示错误详情,可以包含错误信息、时间戳和请求描述等信息。 ```java import java.util.Date; public class ErrorDetails { private Date timestamp; private String message; private String details; public ErrorDetails(Date timestamp, String message, String details) { super(); this.timestamp = timestamp; this.message = message; this.details = details; } // Getters and setters } ``` 3. **抛出自定义异常**: 在控制器中抛出自定义异常,以便 `@ControllerAdvice` 能捕获并处理。 ```java import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api") public class MyController { @GetMapping("/resource") public String getResource() { if (/* some condition */) { throw new ResourceNotFoundException("Resource not found"); } return "Resource content"; } } @ResponseStatus(HttpStatus.NOT_FOUND) public class ResourceNotFoundException extends RuntimeException { public ResourceNotFoundException(String message) { super(message); } } ``` 通过以上步骤,您可以在 Spring Boot 应用中实现集中化的异常处理。`@ControllerAdvice` 注解使得异常处理逻辑能够与控制器逻辑分离,增强了代码的可读性和可维护性。发布于 2024-07-31 16:10 •IP属地 广西举报评论收藏
公众号进入网站体验更佳

