S SmartDocs
Serie: Java java 49 righe · Aggiornato 2026-04-09

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