Koa实例提供给中间件的上下文对象context
,在对客户端返回请求错误的状态码时有两种方式:
context.throw()
context.response.status
这两种方法有两点区别:
response.body的自定义权
使用context.throw()
方法会返回指定的状态码和默认的response.body,而使用context.response.status
设置状态码之后,可以自定义response.body的内容。
如,设置context.throw(404)
状态码,response.body
的内容默认为Not Found
。
各种状态码默认返回的response.body
与规范一致,默认只推荐设置4xx
与5xx
的状态码。
后续逻辑的执行
context.throw()
调用结束后这次响应立即结束,在其后的逻辑不会执行,而通过设置context.response.status
返回错误状态码之后的逻辑依然可以有效执行,可以通过输出到控制台观察到这样的区别。这是因为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);
},