異常處理是建立健全且使用者友好的應用程式的關鍵部分。在 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中文網其他相關文章!