
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ī)范一致,默認只推薦設置4xx與5xx的狀態(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);
},