Koa學(xué)習(xí)筆記:服務(wù)器端錯(cuò)誤狀態(tài)碼返回方式

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

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

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

response.body的自定義權(quán)

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

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

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

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

  /**
   * 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);
  },
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容