xiongwilee / Gracejs

A Nodejs BFF framework, build with koa2(基于koa2的标准前后端分离框架)
https://grace.wilee.me
MIT License
1.39k stars 238 forks source link

`defaultCtrl.js` 里做鉴权时抛出`401`错误,无法进入default err handing! #58

Closed ewxm closed 6 years ago

ewxm commented 6 years ago

router.js 里捕获了错误,抛出的错误无法进入koadefault error handing 中。

middleware/router/lib/router.js

......
       while (ii--) {
          const strckFun = layer.stack[ii];
           try {
            if (strckFun.constructor.name === 'GeneratorFunction') {
              await co(strckFun.bind(ctx))
            } else {
              await strckFun.call(ctx);
            }
           } catch (err) {
             error(err);
             ctx.status = 500;
             ctx.body = 'Controller Execute Error!'
           }
        }
......

app/shop/controller/defaultCtrl.js

const { sid } = require('../../rds');
const level = require('../../../config/level.json');

module.exports = async function () {
    console.log('this is a base controller!');
......
        let xxxxx = await sid.hexists(`xxx:${token}`,'xxxxx');
        if(xxxxx){
            console.log('授权通过!')
        }else{
            const err = new Error(JSON.stringify({ code:Constant.statusCode.FAIL.code, msg: Constant.httpCode.Unauthorized.msg }));
            err.status = 401;
            err.expose = false;
            throw err;
        }
......
}

// 设置为非路由
module.exports.__controller__ = false;

koa/lib/context.js

  /**
   * Default error handling.
   *
   * @param {Error} err
   * @api private
   */

  onerror(err) {
    // don't do anything if there is no error.
  ...
    // force text/plain
    this.type = 'text';

    // ENOENT support
    if ('ENOENT' == err.code) err.status = 404;

    // default to 500
    if ('number' != typeof err.status || !statuses[err.status]) err.status = 500;

    // respond
    const code = statuses[err.status];
    const msg = err.expose ? err.message : code;
    this.status = err.status;
    this.length = Buffer.byteLength(msg);
    this.res.end(msg);
  }
};
xiongwilee commented 6 years ago

收了这个ISSUE, 先干掉router里的try catch吧