В моем index.js я зарегистрировал промежуточное программное обеспечение для обработки ошибок:
Код: Выделить всё
// Error handler middleware (must be after all routes)
app.use(errorHandler);
Код: Выделить всё
const errorHandler = async (err, req, res, next) => {
let errorId = saveErrorToDatabase();
return Responses.internalError(res, `Internal Server Error (ID: ${errorId})`);
};
< /code>
Тогда у меня есть класс контроллера, который мой маршрут указывает на: < /p>
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' });
},
Код: Выделить всё
async insert(name, type) {
return this.#crudDBUtil.insert({ name, type });
}
< /code>
CrudDBUtil{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
< /code>
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?
Подробнее здесь: https://stackoverflow.com/questions/795 ... nd-express
Мобильная версия