Class StandardRestExceptionHandler

java.lang.Object
org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler
io.leandev.appfuse.error.StandardRestExceptionHandler
All Implemented Interfaces:
org.springframework.beans.factory.Aware, org.springframework.context.MessageSourceAware

public abstract class StandardRestExceptionHandler extends org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler

標準 REST API 異常處理器基類 (RFC 7807)

提供統一的異常處理實作,將所有異常轉換為 RFC 7807 ProblemDetail 格式。 應用層可直接使用或繼承擴展。

繼承 ResponseEntityExceptionHandler 以處理 Spring 框架內建異常。

RFC 7807 錯誤回應格式

{
  "type": "urn:appfuse:error:not-found",
  "title": "Not Found",
  "status": 404,
  "detail": "The requested resource does not exist",
  "instance": "/api/users/123",
  "violations": [...],  // 僅在驗證錯誤時包含
  "format": "...",      // 用於國際化
  "params": [...]       // 訊息參數
}

使用方式

方式 1:直接使用(推薦用於簡單應用)

@ControllerAdvice
public class GlobalRestExceptionHandler extends StandardRestExceptionHandler {
}

方式 2:註冊自定義 Mapper(推薦用於需要自定義異常處理的應用)

@ControllerAdvice
public class GlobalRestExceptionHandler extends StandardRestExceptionHandler {
    static {
        getRegistry().register(new CustomBusinessExceptionMapper());
    }
}
See Also:
  • Field Summary

    Fields inherited from class org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler

    logger, PAGE_NOT_FOUND_LOG_CATEGORY, pageNotFoundLogger
  • Constructor Summary

    Constructors
    Constructor
    Description
     
  • Method Summary

    Modifier and Type
    Method
    Description
    protected String
    extractPath(org.springframework.web.context.request.WebRequest request)
    從 WebRequest 提取請求路徑
    protected static ExceptionMappingRegistry
    取得異常映射註冊中心 子類別可透過此方法註冊自定義 Mapper
    protected org.springframework.http.ResponseEntity<Object>
    handleApplicationException(ApplicationException ex, org.springframework.web.context.request.WebRequest request)
    處理應用程式自定義異常 Source: AppFuse - 業務邏輯層拋出的語義化異常 Includes: NotFoundException, ConflictException, DuplicateException, etc.
    protected org.springframework.http.ResponseEntity<Object>
    handleFrameworkException(Exception ex, org.springframework.web.context.request.WebRequest request)
    統一處理 Spring 和 Jakarta 框架異常 Sources:
    protected org.springframework.http.ResponseEntity<Object>
    handleHttpClientException(HttpClientException ex, org.springframework.web.context.request.WebRequest request)
    處理 AppFuse HTTP 客戶端異常 Source: AppFuse HTTP Client - HTTP 客戶端呼叫異常
    protected org.springframework.http.ResponseEntity<Object>
    handleMethodArgumentNotValid(org.springframework.web.bind.MethodArgumentNotValidException ex, org.springframework.http.HttpHeaders headers, org.springframework.http.HttpStatusCode status, org.springframework.web.context.request.WebRequest request)
    處理 @Valid 或 @Validated 驗證失敗 Source: Spring Validation - 當請求體驗證失敗時拋出
    protected org.springframework.http.ResponseEntity<Object>
    handleMissingPathVariable(org.springframework.web.bind.MissingPathVariableException ex, org.springframework.http.HttpHeaders headers, org.springframework.http.HttpStatusCode status, org.springframework.web.context.request.WebRequest request)
    處理路徑變數缺失 Source: Spring Web - 當 @PathVariable 對應的路徑變數缺失時拋出
    protected org.springframework.http.ResponseEntity<Object>
    handleMissingServletRequestParameter(org.springframework.web.bind.MissingServletRequestParameterException ex, org.springframework.http.HttpHeaders headers, org.springframework.http.HttpStatusCode status, org.springframework.web.context.request.WebRequest request)
    處理缺少必要的請求參數 Source: Spring Web - 當 @RequestParam(required=true) 缺失時拋出
    protected org.springframework.http.ResponseEntity<Object>
    handleOtherException(Exception ex, org.springframework.web.context.request.WebRequest request)
    處理所有未捕獲的異常 (兜底處理) Source: 任何未被上述 handler 處理的異常
    protected org.springframework.http.ResponseEntity<Object>
    handleProblemDetail(org.springframework.http.ProblemDetail problem, Throwable cause, org.springframework.web.context.request.WebRequest request)
    統一處理 ProblemDetail 並返回 RFC 7807 格式的 JSON 回應

    Methods inherited from class org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler

    createProblemDetail, createResponseEntity, getMessageSource, handleAsyncRequestNotUsableException, handleAsyncRequestTimeoutException, handleConversionNotSupported, handleErrorResponseException, handleException, handleExceptionInternal, handleHandlerMethodValidationException, handleHttpMediaTypeNotAcceptable, handleHttpMediaTypeNotSupported, handleHttpMessageNotReadable, handleHttpMessageNotWritable, handleHttpRequestMethodNotSupported, handleMaxUploadSizeExceededException, handleMethodValidationException, handleMissingServletRequestPart, handleNoHandlerFoundException, handleNoResourceFoundException, handleServletRequestBindingException, handleTypeMismatch, setMessageSource

    Methods inherited from class Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Constructor Details

    • StandardRestExceptionHandler

      public StandardRestExceptionHandler()
  • Method Details

    • getRegistry

      protected static ExceptionMappingRegistry getRegistry()
      取得異常映射註冊中心 子類別可透過此方法註冊自定義 Mapper
      Returns:
      ExceptionMappingRegistry
    • handleMissingServletRequestParameter

      protected org.springframework.http.ResponseEntity<Object> handleMissingServletRequestParameter(@NonNull org.springframework.web.bind.MissingServletRequestParameterException ex, @NonNull org.springframework.http.HttpHeaders headers, @NonNull org.springframework.http.HttpStatusCode status, @NonNull org.springframework.web.context.request.WebRequest request)
      處理缺少必要的請求參數 Source: Spring Web - 當 @RequestParam(required=true) 缺失時拋出
      Overrides:
      handleMissingServletRequestParameter in class org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler
    • handleMissingPathVariable

      protected org.springframework.http.ResponseEntity<Object> handleMissingPathVariable(@NonNull org.springframework.web.bind.MissingPathVariableException ex, @NonNull org.springframework.http.HttpHeaders headers, @NonNull org.springframework.http.HttpStatusCode status, @NonNull org.springframework.web.context.request.WebRequest request)
      處理路徑變數缺失 Source: Spring Web - 當 @PathVariable 對應的路徑變數缺失時拋出
      Overrides:
      handleMissingPathVariable in class org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler
    • handleMethodArgumentNotValid

      protected org.springframework.http.ResponseEntity<Object> handleMethodArgumentNotValid(@NonNull org.springframework.web.bind.MethodArgumentNotValidException ex, @NonNull org.springframework.http.HttpHeaders headers, @NonNull org.springframework.http.HttpStatusCode status, @NonNull org.springframework.web.context.request.WebRequest request)
      處理 @Valid 或 @Validated 驗證失敗 Source: Spring Validation - 當請求體驗證失敗時拋出
      Overrides:
      handleMethodArgumentNotValid in class org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler
    • handleFrameworkException

      @ExceptionHandler({org.springframework.transaction.TransactionSystemException.class,jakarta.validation.ValidationException.class,org.springframework.dao.DataAccessException.class,org.springframework.http.converter.HttpMessageConversionException.class}) protected org.springframework.http.ResponseEntity<Object> handleFrameworkException(Exception ex, org.springframework.web.context.request.WebRequest request)

      統一處理 Spring 和 Jakarta 框架異常 Sources:

      • TransactionSystemException: Spring Transaction - 事務提交時驗證失敗
      • ValidationException: Jakarta Validation - Bean Validation 驗證失敗
      • DataAccessException: Spring Data - JPA/JDBC 資料庫操作異常
      • HttpMessageConversionException: Spring Web - HTTP 訊息轉換失敗 (如 JSON 解析錯誤)
    • handleHttpClientException

      @ExceptionHandler(HttpClientException.class) protected org.springframework.http.ResponseEntity<Object> handleHttpClientException(HttpClientException ex, org.springframework.web.context.request.WebRequest request)
      處理 AppFuse HTTP 客戶端異常 Source: AppFuse HTTP Client - HTTP 客戶端呼叫異常
    • handleApplicationException

      @ExceptionHandler(ApplicationException.class) protected org.springframework.http.ResponseEntity<Object> handleApplicationException(ApplicationException ex, org.springframework.web.context.request.WebRequest request)
      處理應用程式自定義異常 Source: AppFuse - 業務邏輯層拋出的語義化異常 Includes: NotFoundException, ConflictException, DuplicateException, etc.
    • handleOtherException

      @ExceptionHandler(Exception.class) protected org.springframework.http.ResponseEntity<Object> handleOtherException(Exception ex, org.springframework.web.context.request.WebRequest request)
      處理所有未捕獲的異常 (兜底處理) Source: 任何未被上述 handler 處理的異常
    • handleProblemDetail

      protected org.springframework.http.ResponseEntity<Object> handleProblemDetail(org.springframework.http.ProblemDetail problem, Throwable cause, org.springframework.web.context.request.WebRequest request)
      統一處理 ProblemDetail 並返回 RFC 7807 格式的 JSON 回應
      Parameters:
      problem - ProblemDetail 物件
      cause - 原始異常(用於日誌記錄)
      request - WebRequest(用於取得請求路徑)
    • extractPath

      protected String extractPath(org.springframework.web.context.request.WebRequest request)
      從 WebRequest 提取請求路徑