Koa2 failed to handle the exception unhandled 'error' event

125 Views Asked by At

I learned to use koa2 and koa-json-error to make a simple little thing. I wrote an interface to query the database and throw 404 error when the result is null. However, the node will prompt unhandled 'error' event.

But when I use if (id.length !== 24 || !mongoose.Types.ObjectId.isValid(id)) { ctx.throw(412, 'id长度不是24或不是有效对象') }; , it works

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;
    })
}

1

There are 1 best solutions below

0
On

I see a solution and I will try it

"You're throwing asynchronously inside the callback. "

In the end, it's settled like this.

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