GlobalExceptionHandler.java
Java/Baasid/src/main/java/com/baasid/exception/GlobalExceptionHandler.java
package com.baasid.exception;
import com.baasid.dto.ErrorResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* 全域例外處理:將業務與驗證例外轉為統一 JSON 格式 {@link ErrorResponse} 與對應 HTTP 狀態碼。
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
/** 登入失敗等未授權情境 → 401。 */
@ExceptionHandler(UnauthorizedException.class)
public ResponseEntity<ErrorResponse> handleUnauthorized(UnauthorizedException e) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
.body(new ErrorResponse(401, e.getMessage()));
}
/** 資源不存在 → 404。 */
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ErrorResponse> handleNotFound(ResourceNotFoundException e) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(new ErrorResponse(404, e.getMessage()));
}
/**
* {@code @Valid} 驗證失敗(例如欄位為空)→ 400,訊息為各欄位錯誤合併字串。
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ErrorResponse> handleValidation(MethodArgumentNotValidException e) {
String message = e.getBindingResult().getFieldErrors().stream()
.map(err -> err.getField() + ": " + err.getDefaultMessage())
.reduce((a, b) -> a + "; " + b)
.orElse("驗證失敗");
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(new ErrorResponse(400, message));
}
/** 其餘未預期例外 → 500,不對外洩漏堆疊細節。 */
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleGeneral(Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(new ErrorResponse(500, "系統錯誤"));
}
}
Articoli correlati
init.sql
init.sql — sql source code from the Java learning materials (Java/Baasid/sql/init.sql).
Leggi l'articolo →BaasidApplication.java
BaasidApplication.java — java source code from the Java learning materials (Java/Baasid/src/main/java/com/baasid/BaasidApplication.java).
Leggi l'articolo →DataInitializer.java
DataInitializer.java — java source code from the Java learning materials (Java/Baasid/src/main/java/com/baasid/config/DataInitializer.java).
Leggi l'articolo →OpenApiConfig.java
OpenApiConfig.java — java source code from the Java learning materials (Java/Baasid/src/main/java/com/baasid/config/OpenApiConfig.java).
Leggi l'articolo →SecurityConfig.java
SecurityConfig.java — java source code from the Java learning materials (Java/Baasid/src/main/java/com/baasid/config/SecurityConfig.java).
Leggi l'articolo →AuthController.java
AuthController.java — java source code from the Java learning materials (Java/Baasid/src/main/java/com/baasid/controller/AuthController.java).
Leggi l'articolo →