Spaces:
Running
Running
File size: 897 Bytes
c89bb66 7a555a5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import { AppError } from './errors.js';
// Lets controllers be plain async functions: a thrown error or rejected promise reaches errorHandler
export const asyncHandler = (fn) => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next);
// Registered last in index.js
export function errorHandler(err, req, res, next) {
if (res.headersSent) return next(err);
if (err instanceof AppError) {
return res.status(err.status).json({ error: err.code, message: err.message });
}
// express.json() payload problems (too large, malformed JSON) carry their own 4xx status
if (err.status >= 400 && err.status < 500) {
return res.status(err.status).json({ error: 'BAD_REQUEST', message: err.message });
}
console.error('[Unhandled Error]', err);
res.status(500).json({ error: 'INTERNAL_ERROR', message: 'Something went wrong on the server.' });
}
|