2016-10-19 215 views
0

我有以下功能在我的应用程序中创建用户,我试图检测是否已经创建了管理员用户并阻止创建另一个用户。当处理错误时未处理的“错误”事件

export async function createUser (ctx) { 
    if (ctx.request.body.type == undefined ) { 
     ctx.throw(400, 'Bad Request') 
    } 
    if (ctx.request.body.type === 'admin') { 
    User.findOne({type:'admin'}, (err, usr) => { 
     if (err) 
     ctx.throw(422, err.message) 
     if (usr){ 
     ctx.throw(400, 'Duplicate Admin') 
     } 
    }) 
    } 
.... 

第一ctx.throw(400, 'Bad Request')作品,但如果其他管理员用户找到该ctx.throw(400, 'Duplicate Admin')会引起以下错误,崩溃的应用程序:

events.js:160 
     throw er; // Unhandled 'error' event 
    ^

BadRequestError: Duplicate Admin 

我要把错误在地不足?是什么原因导致第一次投掷没有崩溃而不是第二次?

预先感谢任何帮助

回答

0

你的User.findOne回调异步里面扔。这崩溃了。

取而代之的是,看看你正在使用的库,它会给你User.findOne,看它是否可以返回一个承诺,或者如果它不包含在蓝鸟的Promise.promisify中。

这是要在抵达代码:

const user = await User.findOne({ type: 'admin' }) // returns a promise 
if (user) ctx.throw(400, 'Duplicate admin') 
0

首先,检查“用户” variable.If一个数组或对象的类型,if(user){....}将始终返回true,即使它是空的。并尝试添加

app.on('error', function() { 
    console.log('yep this is an error'); 
}); 

事件侦听器