Build APIS YOU WONT HATE Status Codes, Errors and Messages 筆記 - fantasy0107/notes GitHub Wiki

當成功或失敗都必須要讓人知道,有以下兩個部分

  1. HTTP status codes
  2. Custom error codes and messages

書中範例

Code Text Description
161 你不能追隨這個使用者 403 status code
179 你沒有授權去看這個 403 status code

JSON-API

是一個標準主要是針對 requests 和 responses 的格式

錯誤格式可能有以下屬性

  • id
  • href
  • status
  • code
  • title
  • detail
  • links
  • path

2XX success

  • 200 - 通用 - Generic everything is OK
  • 201 - 建立資源 - Created something OK
  • 202 - 接受請求但非同步執行 - Accepted but is being processed async

3XX redirection

4XX client errors

  • 400 - 通用 -Bad Request (should really be for invalid syntax, but some folks use for validation)
  • 401 - 沒授權 - Unauthorized (no current user and there should be)
  • 403 - 禁止 -The current user is forbidden from accessing this data
  • 404 - 不正確的route- That URL is not a valid route, or the item resource does not exist
  • 405 - Method Not Allowed (your framework will probably do this for you)
  • 410 - 資料已經刪除 - Data has been deleted, deactivated, suspended, etc.

5XX service errors

  • 500 - Something unexpected happened, and it is the APIs fault
  • 503 - API is not here right now, please try again later