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è)置4xx
與5xx
的狀態(tài)碼。
后續(xù)邏輯的執(zhí)行
context.throw()
調(diào)用結(jié)束后這次響應(yīng)立即結(jié)束徘意,在其后的邏輯不會(huì)執(zhí)行苔悦,而通過(guò)設(shè)置context.response.status
返回錯(cuò)誤狀態(tài)碼之后的邏輯依然可以有效執(zhí)行,可以通過(guò)輸出到控制臺(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);
},