首页 > 解决方案 > npm mysql 库中抛出的错误导致崩溃 - throw err; // 重新抛出非 MySQL 错误

问题描述

我现在一直在将该mysql库用于一个项目。我注意到了一些东西。

    try {
        let number = req.params.number;
        number = parseInt(number, 10);
        if (number && number % 10 == 0 && number > 0) {
            pool.query(
                `select * from posts limit ${number - 10}, ${10}`,
                function (err, result) {
                    if (err) {
                        throw "Url incorrect, ensure that the params % 10 == 0";
                    }
                    // if (!result.length) {
                    //  throw "No more posts available";
                    // }
                    const response = result.map(function (item) {
                        return {
                            ...item,
                            files: item.files
                                ? item.files.split(",").map(function (item) {
                                        return (
                                            "http://localhost:4000/files/" +
                                            item
                                        );
                                  })
                                : [],
                        };
                    });
                    res.json({
                        valid: true,
                        data: response,
                        nextPage: number + 10,
                    });
                }
            );
        } else {
            throw "Something went wrong";
        }
    } catch (err) {
        console.log(err);
        res.json({ valid: false, msg: err });
    }

这是我的代码的一部分。在这里,当结果的长度为 0 时,我会抛出错误并将其 console.log 到 catch 块中。但我注意到它使程序崩溃并throw err; // Rethrow non-MySQL errors ^ No more posts available (Use `node --trace-uncaught ...` to show where the exception was thrown) npm ERR! code ELIFECYCLE.......在终端中打印。我不明白我犯了什么错误?

标签: mysqlnode.jsnpmtry-catchthrow

解决方案


推荐阅读