REST API 錯誤處理最佳實踐

Architecture,REST
Remote
1
07:25 AM · Dec 01 ,2025

1. 概述

REST 是一種無狀態架構,客户端可以訪問和操作服務器上的資源。通常,RESTful 服務使用 HTTP 來宣佈他們管理的一組資源,並提供一個 API,允許客户端獲取或修改這些資源的當前狀態。

在本教程中,我們將學習處理 REST API 錯誤的一些最佳實踐,包括為用户提供相關信息的一些有用的方法,來自大型網站的示例以及使用 Spring REST 應用程序的實際實現。

2. HTTP 狀態碼

當客户端向 HTTP 服務器發送請求,且服務器成功接收到該請求時,服務器必須通知客户端請求是否成功處理或未處理。

HTTP 通過五類狀態碼來實現這一點:

  • 100-級別 (信息) – 服務器確認請求
  • 200-級別 (成功) – 服務器已按照預期完成請求
  • 300-級別 (重定向) – 客户端需要執行進一步操作以完成請求
  • 400-級別 (客户端錯誤) – 客户端發送了無效請求
  • 500-級別 (服務器錯誤) – 由於服務器端錯誤,未能完成有效的請求

根據響應代碼,客户端可以推斷出特定請求的結果。

3. Handling Errors

The first step in handling errors is to provide a client with a proper status code. Additionally, we may need to provide more information in the response body.

3.1. Basic Responses

The simplest way we handle errors is to respond with an appropriate status code.

Here are some common response codes:

  • 400 Bad Request – client sent an invalid request, such as lacking required request body or parameter
  • 401 Unauthorized – client failed to authenticate with the server
  • 403 Forbidden – client authenticated but does not have permission to access the requested resource
  • 404 Not Found – the requested resource does not exist
  • 412 Precondition Failed – one or more conditions in the request header fields evaluated to false
  • 500 Internal Server Error – a generic error occurred on the server
  • 503 Service Unavailable – the requested service is not available

While basic, these codes allow a client to understand the broad nature of the error that occurred. We know that if we receive a 403 error, for example, we lack permissions to access the resource we requested. In many cases, though, we need to provide supplemental details in our responses.

500 errors signal that some issues or exceptions occurred on the server while handling a request. Generally, this internal error is not our client’s business.

Therefore, to minimize these kinds of responses to the client, we should diligently attempt to handle or catch internal errors and respond with other appropriate status codes wherever possible.

For example, if an exception occurs because a requested resource doesn’t exist, we should expose this as a 404 rather than a 500 error.

This is not to say that 500 should never be returned, only that it should be used for unexpected conditions — such as a service outage — that prevent the server from carrying out the request.

3.2. Default Spring Error Responses

These principles are so ubiquitous that Spring has codified them in its default error handling mechanism.

To demonstrate, suppose we have a simple Spring REST application that manages books, with an endpoint to retrieve a book by its ID:

curl -X GET -H "Accept: application/json" http://localhost:8082/spring-rest/api/book/1

If there is no book with an ID of 1, we expect that our controller will throw a BookNotFoundException.

Performing a GET on this endpoint, we see that this exception was thrown, and this is the response body:

{
    "timestamp":"2019-09-16T22:14:45.624+0000",
    "status":500,
    "error":"Internal Server Error",
    "message":"No message available",
    "path":"/api/book/1"
}

Note that this default error handler includes a timestamp of when the error occurred, the HTTP status code, a title (the error field), a message if messages are enabled in the default error (and is blank by default), and the URL path where the error occurred.

These fields provide a client or developer with information to help troubleshoot the problem and also constitute a few of the fields that make up standard error handling mechanisms.

Also note that Spring automatically returns an HTTP status code of 500 when our BookNotFoundException is thrown. Although some APIs will return a 500 status code or other generic ones, as we will see with the Facebook and Twitter APIs, for all errors for the sake of simplicity, it is best to use the most specific error code when possible.

In our example, we can add a @ControllerAdvice so that when a BookNotFoundException is thrown, our API gives back a status of 404 to denote Not Found instead of 500 Internal Server Error.

3.3. More Detailed Responses

As seen in the above Spring example, sometimes a status code is not enough to show the specifics of the error. When needed, we can use the body of the response to provide the client with additional information.

When providing detailed responses, we should include:

  • Error – a unique identifier for the error
  • Message – a brief human-readable message
  • Detail – a lengthier explanation of the error

For example, if a client sends a request with incorrect credentials, we can send a 401 response with this body:

{
    "error": "auth-0001",
    "message": "Incorrect username and password",
    "detail": "Ensure that the username and password included in the request are correct"
}

error field should not match the response code">The error field should not match the response code. Instead, it should be an error code unique to our application. Generally, there is no convention for the error field, expect that it be unique.

Usually, this field contains only alphanumerics and connecting characters, such as dashes or underscores. For example, 0001, auth-0001 and incorrect-user-pass are canonical examples of error codes.

message portion of the body is usually considered presentable on user interfaces">The message portion of the body is usually considered presentable on user interfaces. Therefore, we should translate this title if we support internationalization. So if a client sends a request with an Accept-Language header corresponding to French, the title value should be translated to French.

detail portion is intended for use by developers of clients and not the end user">The detail portion is intended for use by developers of clients and not the end user, so the translation is not necessary.

Additionally, we could also provide a URL — such as the help field — that clients can follow to discover more information:

{
    "error": "auth-0001",
    "message": "Incorrect username and password",
    "detail": "Ensure that the username and password included in the request are correct",
    "help": "https://example.com/help/error/auth-0001"
}

Sometimes, we may want to report more than one error for a request.

In this case, we should return the errors in a list:

{
    "errors": [
        {
            "error": "auth-0001",
            "message": "Incorrect username and password",
            "detail": "Ensure that the username and password included in the request are correct",
            "help": "https://example.com/help/error/auth-0001"
        },
        ...
    ]
}

And when a single error occurs, we respond with a list containing one element.

Note that responding with multiple errors may be too complicated for simple applications. In many cases, responding with the first or most significant error is sufficient.

3.4. Standardized Response Bodies

While most REST APIs follow similar conventions, specifics usually vary, including the names of fields and the information included in the response body. These differences make it difficult for libraries and frameworks to handle errors uniformly.

In an effort to standardize REST API error handling, RFC 7807, which creates a generalized error-handling schema">the IETF devised RFC 7807, which creates a generalized error-handling schema

This schema is composed of five parts:

  1. type – a URI identifier that categorizes the error
  2. title – a brief, human-readable message about the error
  3. status – the HTTP response code (optional)
  4. detail – a human-readable explanation of the error
  5. instance – a URI that identifies the specific occurrence of the error

Instead of using our custom error response body, we can convert our body:

{
    "type": "/errors/incorrect-user-pass",
    "title": "Incorrect username or password.",
    "status": 401,
    "detail": "Authentication failed due to incorrect username or password.",
    "instance": "/login/log/abc123"
}

Note that the type field categorizes the type of error, while instance identifies a specific occurrence of the error in a similar fashion to classes and objects, respectively.

By using URIs, clients can follow these paths to find more information about the error in the same way that HATEOAS links can be used to navigate a REST API.

Adhering to RFC 7807 is optional, but it is advantageous if uniformity is desired.

4. 示例

上述實踐在許多流行的 REST API 中都很常見。雖然字段或格式的具體名稱在不同站點之間可能有所不同,但總體模式幾乎是普遍存在的。

4.1. 推特

讓我們發送一個 GET 請求,而沒有提供所需的身份驗證數據:

curl -X GET https://api.twitter.com/1.1/statuses/update.json?include_entities=true

推特 API 響應包含以下內容:

 {
    "errors": [
        {
            "code":215,
            "message":"身份驗證數據無效。"
        }
    ]
}

此響應包含一個列表,其中包含一個錯誤,其錯誤代碼和消息。在推特的情況下,沒有提供詳細消息,而是使用通用的錯誤——而不是更具體的 401 錯誤——來表示身份驗證失敗。

有時,更通用的狀態碼更容易實現,如我們在 Spring 示例中看到的。它允許開發人員捕獲異常組,而無需區分應返回的狀態碼。但是,在可能的情況下,應使用最具體的狀態碼。

4.2. 臉書

與推特類似,臉書的 Graph REST API 也包含其響應中的詳細信息。

讓我們執行一個 POST 請求,以使用臉書 Graph API 進行身份驗證:

curl -X GET https://graph.facebook.com/oauth/access_token?client_id=foo&client_secret=bar&grant_type=baz

我們收到以下錯誤:

 {
    "error": {
        "message": "缺少 redirect_uri 參數。",
        "type": "OAuthException",
        "code": 191,
        "fbtrace_id": "AWswcVwbcqfgrSgjG80MtqJ"
    }
}

與推特類似,臉書也使用通用的錯誤——而不是更具體的 400 級錯誤——來表示失敗。除了消息和數字代碼外,臉書還包括一個type 字段,用於對錯誤進行分類,以及一個跟蹤 ID (fbtrace_id),作為內部支持標識符

5. 結論

在本文中,我們探討了 REST API 錯誤處理的最佳實踐:

  • 提供具體的狀態碼
  • 在響應體中包含額外信息
  • 以統一的方式處理異常

雖然錯誤處理的細節會因應用程序而異,但這些通用原則適用於幾乎所有 REST API,並在可能時應遵循

這不僅允許客户端以一致的方式處理錯誤,還簡化了我們在實施 REST API 時編寫的代碼。

user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.