Fix 500 error logging to show actual error instead of generic message
pino-http checks res.err before falling back to its generic "failed with status code 500" error. Set res.err to the real error in the error handler so logs include the actual message and stack trace. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -10,6 +10,9 @@ export function errorHandler(
|
||||
_next: NextFunction,
|
||||
) {
|
||||
if (err instanceof HttpError) {
|
||||
if (err.status >= 500) {
|
||||
(res as any).err = err;
|
||||
}
|
||||
res.status(err.status).json({
|
||||
error: err.message,
|
||||
...(err.details ? { details: err.details } : {}),
|
||||
@@ -26,8 +29,10 @@ export function errorHandler(
|
||||
? { message: err.message, stack: err.stack, name: err.name }
|
||||
: { raw: err };
|
||||
|
||||
// Attach the real error so pino-http can include it in its response log
|
||||
res.locals.serverError = errObj;
|
||||
// Attach the real error so pino-http uses it instead of its generic
|
||||
// "failed with status code 500" message in the response-complete log
|
||||
const realError = err instanceof Error ? err : Object.assign(new Error(String(err)), { raw: err });
|
||||
(res as any).err = realError;
|
||||
|
||||
logger.error(
|
||||
{ err: errObj, method: req.method, url: req.originalUrl },
|
||||
|
||||
@@ -55,11 +55,7 @@ export const httpLogger = pinoHttp({
|
||||
customErrorMessage(req, res) {
|
||||
return `${req.method} ${req.url} ${res.statusCode}`;
|
||||
},
|
||||
customProps(_req, res) {
|
||||
const serverError = (res as any).locals?.serverError;
|
||||
if (serverError) {
|
||||
return { serverError };
|
||||
}
|
||||
customProps() {
|
||||
return {};
|
||||
},
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user