3.3.6.Walkthrough: Implementation of error handling for POST API

  • 如果POST失敗, 只回400是不夠的, 為了讓開發找更能addressing issue, Steps to improve POST error handling

    • 1.Steup the error codes and description for API specific errors

    • 2.Create the template for the error response body

    • 3.Code a utility function for creating the error response

    • 4.Implement the error handling code for POST /vacations

      • Send back status code for duplicate & vacation errors

  • 建議使用的status code

    • code 5000: unknown Error

    • code 6xxx: Any database error such as duplicate keys

    • code 7xxx: Validation error

  • 程式碼解析

    • api/v1/vacation

      • 1.在POST方法中

        • 1.建立了useError物件

        • 2.在Response中設定Content-Type: "application/json"

      • 2.宣告函數表達式processMongooseErrors: 回傳error物件

      • 3.宣告函數表達式processValidationErrors: 處理Validation Error

  • util/error

    • 1.建立error list物件

    • 2.create方法會回傳text:message, timestamp, method, endpoint, errors, payload

    • 結果

Last updated

Was this helpful?