异常处理是构建健壮且用户友好的应用程序的关键部分。在 Spring Boot 中,我们可以通过多种方式处理异常,以确保我们的应用程序保持稳定并向用户提供有意义的反馈。本指南将涵盖异常处理的不同策略,包括自定义异常、全局异常处理、验证错误和生产最佳实践。
异常是破坏程序正常流程的事件。它们可以分为:
创建自定义异常类有助于处理应用程序中的特定错误情况。
package com.example.SpringBootRefresher.exception; public class DepartmentNotFoundException extends RuntimeException { public DepartmentNotFoundException(String message) { super(message); } }
@ExceptionHandler 注解:
您可以在控制器类中定义处理异常的方法。
package com.example.SpringBootRefresher.controller; import com.example.SpringBootRefresher.exception.DepartmentNotFoundException; 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 DepartmentController { @GetMapping("/department") public String getDepartment() { // Simulate an exception throw new DepartmentNotFoundException("Department not found!"); } @ExceptionHandler(DepartmentNotFoundException.class) public ResponseEntity<String> handleDepartmentNotFoundException(DepartmentNotFoundException ex) { return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND); } }
要全局处理异常,您可以使用@ControllerAdvice和集中式异常处理程序。
package com.example.SpringBootRefresher.error; import com.example.SpringBootRefresher.entity.ErrorMessage; import com.example.SpringBootRefresher.exception.DepartmentNotFoundException; 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.ResponseStatus; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; @ControllerAdvice @ResponseStatus public class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler { @ExceptionHandler(DepartmentNotFoundException.class) public ResponseEntity<ErrorMessage> handleDepartmentNotFoundException(DepartmentNotFoundException exception, WebRequest request) { ErrorMessage message = new ErrorMessage( HttpStatus.NOT_FOUND.value(), exception.getMessage(), request.getDescription(false) ); return ResponseEntity.status(HttpStatus.NOT_FOUND) .body(message); } @ExceptionHandler(Exception.class) public ResponseEntity<ErrorMessage> handleGlobalException(Exception exception, WebRequest request) { ErrorMessage message = new ErrorMessage( HttpStatus.INTERNAL_SERVER_ERROR.value(), exception.getMessage(), request.getDescription(false) ); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body(message); } }
定义标准错误响应类来构建错误消息。
package com.example.SpringBootRefresher.entity; public class ErrorMessage { private int statusCode; private String message; private String description; public ErrorMessage(int statusCode, String message, String description) { this.statusCode = statusCode; this.message = message; this.description = description; } // Getters and setters public int getStatusCode() { return statusCode; } public void setStatusCode(int statusCode) { this.statusCode = statusCode; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
Spring Boot 与 Bean Validation (JSR-380) 集成良好。要全局处理验证错误,请使用@ControllerAdvice。
package com.example.SpringBootRefresher.error; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.context.request.WebRequest; import java.util.HashMap; import java.util.Map; @ControllerAdvice @ResponseStatus public class ValidationExceptionHandler extends ResponseEntityExceptionHandler { @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<Map<String, String>> handleValidationExceptions(MethodArgumentNotValidException ex) { Map<String, String> errors = new HashMap<>(); ex.getBindingResult().getAllErrors().forEach((error) -> { String fieldName = ((FieldError) error).getField(); String errorMessage = error.getDefaultMessage(); errors.put(fieldName, errorMessage); }); return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST); } }
对于简单的情况,可以用@ResponseStatus注解异常类来指定HTTP状态码。
package com.example.SpringBootRefresher.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(HttpStatus.NOT_FOUND) public class DepartmentNotFoundException extends RuntimeException { public DepartmentNotFoundException(String message) { super(message); } }
Spring Boot 中的异常处理涉及使用 @ExceptionHandler、@ControllerAdvice 和 @ResponseStatus 等注释来有效地管理错误。通过创建自定义异常、处理验证错误并遵循最佳实践,您可以构建强大的应用程序,以优雅地处理错误并向用户提供有意义的反馈。使用 Java 17 功能可确保您的应用程序利用 Java 生态系统中的最新改进。
以上是Spring Boot 中的异常处理的详细内容。更多信息请关注PHP中文网其他相关文章!