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

Koa实例提供给中间件的上下文对象context,在对客户端返回请求错误的状态码时有两种方式:git

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

这两种方法有两点区别:github

response.body的自定义权

使用context.throw()方法会返回指定的状态码和默认的response.body,而使用context.response.status设置状态码以后,能够自定义response.body的内容。api

如,设置context.throw(404)状态码,response.body的内容默认为Not Found
各类状态码默认返回的response.body与规范一致,默认只推荐设置4xx5xx的状态码。ui

后续逻辑的执行

context.throw()调用结束后此次响应当即结束,在其后的逻辑不会执行,而经过设置context.response.status返回错误状态码以后的逻辑依然能够有效执行,能够经过输出到控制台观察到这样的区别。这是由于throw方法是直接抛出错误,可从官方源码里看出:this

/**
   * 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);
  },
相关文章
相关标签/搜索