NodeJS выбрасывает UnhandledPromiseRejectionWarning, когда я обращаюсь к ошибке - PullRequest
0 голосов
/ 22 октября 2019

Я хочу обработать ошибку, когда пользователь преднамеренно ввел неправильный objectId, но когда я сжал ошибку в проверке функции objectID, я получил эту ошибку: UnhandledPromiseRejectionWarning: Ошибка: INVALID_ID

проверка функции obejctID:

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

1 Ответ

0 голосов
/ 22 октября 2019

Попробуйте использовать try catch:

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