admin管理员组文章数量:1362552
I'm creating a Node.js app with Express and trying to implement an error handling routine. It works with test errors I throw from my controller, but when a real error occurs, my error handling middleware doesn't catch it. Instead, the console prints the error and the server stops. This would be a major problem in production if any error causes the server to crash.
I think the issue might be related to the async methods I'm calling. Here's what I've done:
In my index.js
, I've registered the error handling middleware:
// Error handler middleware (must be after all routes)
app.use(errorHandler);
My errorHandler
middleware (works when the test error was thrown):
const errorHandler = async (err, req, res, next) => {
let errorId = saveErrorToDatabase();
return Responses.internalError(res, `Internal Server Error (ID: ${errorId})`);
};
Then I have my controller class that my route points to:
async create(req, res, next) {
const { name, type } = req.body;
const inserted_id = await (new Account()).insert(name, type);
Responses.success(res, 201, { id: inserted_id, message: 'Account created successfully' });
},
My Account
object:
async insert(name, type) {
return this.#crudDBUtil.insert({ name, type });
}
CrudDBUtil
is a class I created to handle database operations. The insert operation is generating an error (a required field wasn't provided). I expected the API to respond with "Internal Server Error: ID 9999" and save the error in the database. Instead, I'm getting this error (parts omitted for clarity and privacy):
{my full path}\pool.js:36
const localErr = new Error();
^
Error: Field 'user_id' doesn't have a default value
at {Full Call stack} {
code: 'ER_NO_DEFAULT_FOR_FIELD',
errno: 1364,
sql: '{sql sentence}",
sqlState: 'HY000',
sqlMessage: "Field 'user_id' doesn't have a default value"
}
Node.js v20.17.0
My issue isn't with the error itself - I know what it is and how to fix it. However, I want future errors to be registered in the database and, most importantly, not cause the server to stop running. How can I make sure my error handler catches all errors, including those from async operations?
本文标签: javascriptHandling async errors on Nodejs and expressStack Overflow
版权声明:本文标题:javascript - Handling async errors on Node.js and express - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743832781a2546830.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论