Skip to content

Commit aa8569c

Browse files
committed
fix: safer error formatting (PL-000) (#111)
<!-- You can erase any parts of this template not applicable to your Pull Request. --> **Fixes or implements VF-XXX** ### Brief description. What is this change? I found that sometimes `req.id` was undefined, which caused this to throw. Added an optional chaining operator. Also added a `try/catch` as a _real_ safety net. Co-authored-by: Tyler Stewart <[email protected]>
1 parent 8afff01 commit aa8569c

File tree

1 file changed

+14
-8
lines changed

1 file changed

+14
-8
lines changed

src/middlewares/exception/index.ts

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,17 +10,23 @@ export class ExceptionMiddleware extends AbstractMiddleware<never, never> {
1010
}
1111

1212
public handleError(err: unknown, req: Request, res: Response, _next: NextFunction): void {
13-
log.error(`Exception formatter (pre) ${JSON.stringify(err)}`);
13+
try {
14+
log.error(`Exception formatter (pre) ${JSON.stringify(err)}`);
1415

15-
const { statusCode, ...body } = formatError(err);
16+
const { statusCode, ...body } = formatError(err);
1617

17-
const error = {
18-
...body,
19-
requestID: req.id.toString(),
20-
};
18+
const error = {
19+
...body,
20+
requestID: req.id?.toString(),
21+
};
2122

22-
log.error(`Exception formatter (post) ${JSON.stringify(error)}`);
23+
log.error(`Exception formatter (post) ${JSON.stringify(error)}`);
2324

24-
res.status(statusCode).send(error);
25+
res.status(statusCode).send(error);
26+
} catch {
27+
res.status(500).send({
28+
error: err,
29+
});
30+
}
2531
}
2632
}

0 commit comments

Comments
 (0)