異常處理是建立健壯且用戶友好的應用程式的關鍵部分。在 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 ResponseEntityhandleDepartmentNotFoundException(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 ResponseEntityhandleDepartmentNotFoundException(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 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
對於簡單的情況,可以透過@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 生態系統中的最新改進。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3