Koa學習筆記:服務器端錯誤狀態(tài)碼返回方式

Koa實例提供給中間件的上下文對象context,在對客戶端返回請求錯誤的狀態(tài)碼時有兩種方式:

  • context.throw()
  • context.response.status

這兩種方法有兩點區(qū)別:

response.body的自定義權

使用context.throw()方法會返回指定的狀態(tài)碼和默認的response.body,而使用context.response.status設置狀態(tài)碼之后,可以自定義response.body的內(nèi)容。

如,設置context.throw(404)狀態(tài)碼,response.body的內(nèi)容默認為Not Found
各種狀態(tài)碼默認返回的response.body與規(guī)范一致,默認只推薦設置4xx5xx的狀態(tài)碼。

后續(xù)邏輯的執(zhí)行

context.throw()調(diào)用結束后這次響應立即結束,在其后的邏輯不會執(zhí)行,而通過設置context.response.status返回錯誤狀態(tài)碼之后的邏輯依然可以有效執(zhí)行,可以通過輸出到控制臺觀察到這樣的區(qū)別。這是因為throw方法是直接拋出錯誤,可從官方源碼里看出:

  /**
   * Throw an error with `msg` and optional `status`
   * defaulting to 500. Note that these are user-level
   * errors, and the message may be exposed to the client.
   *
   *    this.throw(403)
   *    this.throw('name required', 400)
   *    this.throw(400, 'name required')
   *    this.throw('something exploded')
   *    this.throw(new Error('invalid'), 400);
   *    this.throw(400, new Error('invalid'));
   *
   * See: https://github.com/jshttp/http-errors
   *
   * @param {String|Number|Error} err, msg or status
   * @param {String|Number|Error} [err, msg or status]
   * @param {Object} [props]
   * @api public
   */

  throw(...args) {
    throw createError(...args);
  },
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容