Node抛出错误时NodeJS抛出UnhandledPromiseRejectionWarning
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Node抛出错误时NodeJS抛出UnhandledPromiseRejectionWarning相关的知识,希望对你有一定的参考价值。
当用户有意输入错误的objectId时,我想处理该错误,但是当我在函数检查objectID中压缩该错误时,出现此错误:UnhandledPromiseRejectionWarning:错误:INVALID_ID
功能检查对象ID:
function checkObjectId(...ids)
ids.forEach(id =>
const objectId = mongoose.Types.ObjectId.isValid(id);
if (!objectId) throw new MyError('INVALID_ID',404);
);
服务:
static async updateAuthor(_id, content)
checkObjectId(_id);
const author = await Author.findByIdAndUpdate(_id, content, new: true );
if (!author) throw new MyError('CAN_NOT_FIND_AUTHOR', 404);
return author;
路由器:
routerAuthor.put('/:_id',async (req, res) =>
AuthorService.updateAuthor(req.params._id,req.body)
.then(author => res.send(success : true, author))
.catch(res.onError);
);
app.use((req, res, next) =>
res.onError = function(error)
const body = success: false, message: error.message ;
if (!error.statusCode) console.log(error);
res.status(error.statusCode || 500).send(body);
;
next();
);
答案
static async updateAuthor(_id, content)
try
checkObjectId(_id);
const author = await Author.findByIdAndUpdate(_id, content, new: true );
if (!author) throw new MyError('CAN_NOT_FIND_AUTHOR', 404);
return author;
catch (e)
throw new Error(e);
以上是关于Node抛出错误时NodeJS抛出UnhandledPromiseRejectionWarning的主要内容,如果未能解决你的问题,请参考以下文章
Sequelize NodeJS 服务器抛出“ERR_UNKNOWN_ENCODING”错误