状态(Status)

为了方便用户对 response不同状态码情况和错误进行处理,Uma提供了状态处理插件 plugin-status

安装

$ npm install -S @umajs/plugin-status
1

开启

在 plugin.config.ts 中开启 plugin-status 插件

// plugin.config.ts
export default {
  status: true,
}
1
2
3
4

具体开启方式请参考plugin一节中的配置方式

配置

type statusOptions = {
  /**
   * 前缀
   * 默认:_
   */
  prefix?: string,

  /**
   * 状态或者错误调用方法
   * 错误方法参数 (err, ctx, next)
   * 状态方法参数 (ctx, next)
   */
  [key: string]: string | Function,
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

plugin-status 插件通过对不同状态码设置处理函数的方式来实现统一处理,函数名需要按照${prefix}状态码的格式来命令

例如,在${URSA_ROOT}/config/${URSA_ENV}目录下创建status.config.ts(也可以在 plugin.config.ts 的 status.options 配置)

// status.config.ts
export default <statusOptions>{
    // ===> 404状态码处理方法
    _404(ctx) {
        return ctx.render('404.html');
    }
}
1
2
3
4
5
6
7

上面的配置为状态码 404 的请求添加了统一处理,当请求 404 的时候会返回 404.html 页面,函数接收ctx作为参数,开发者可以根据自己业务情况进行不同处理

除了对不同状态码情况进行处理外,插件还能对未捕获的错误进行处理

在上面的status.config.ts中添加_error方法可以捕获到未被捕获的错误

// status.config.ts
import { IContext } from "@umajs/core";

export default {
    _404(ctx: IContext) {
        return ctx.render('404.html');
    }
    // ===> 未被捕获错误
    _error(e: Error, ctx: IContext) {
        // ...
    }
}
1
2
3
4
5
6
7
8
9
10
11
12

异常errorHanding一节中我们介绍了@Around 可以用来处理方法调用时发生的异常,当方法使用了@Around进行修饰在代码中使用了try-catch,plugin-status 中配置的_error方法就不会被调用,plugin-status 的只会捕获到未 catch 住的错误