Koa学习笔记:服务器端错误状态码返回方式

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与规范一致,默认只推荐设置4xx5xx的状态码。

后续逻辑的执行

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);
  },
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值