Koa2 未能处理异常 unhandled 'error' 事件

问题描述

我学会了使用 koa2 和 koa-json-error 来制作一个简单的小东西。 我写了一个接口查询数据库,结果为空时抛出404错误。 但是节点会提示未处理的'error'事件。

但是当我使用 if (id.length !== 24 || !mongoose.Types.ObjectId.isValid(id)) { ctx.throw(412,'id长度不是24或不是有效对象') }; 时,它有效

async function findById(ctx) {
    //参数校验
    await ctx.verifyParams({
        id: { type: 'string',required: true },})

    let id = ctx.params.id;
    //验证是否有效id
    if (id.length !== 24 || !mongoose.Types.ObjectId.isValid(id)) {
        ctx.throw(412,'id长度不是24或不是有效对象')
    };
    await School.findById(id,(err,schools) => {
        if (err) {
            ctx.throw(err);
        } else if (schools === null) {
            // ctx.status = 404;
            // ctx.message = '没有找到这个学校';
            ctx.throw(404,'没有找到这个学校')
        }
        ctx.body = schools;
    })
}

解决方法

我看到了一个解决方案,我会尝试

“您在回调中异步抛出。”

最后就这样解决了。

const school = await School.findById(id,(err) => {
        if (err) {
            ctx.throw(err);
        }
    });
    if (!school) {
        ctx.throw(404,'没有找到这个学校')
    }
    ctx.body = school;