Skip to content

Commit af8756b

Browse files
author
shenald-dev
committed
fix: add JSON 404 and error handlers for consistent API responses
Unknown routes now return JSON {error: 'Not found'} instead of Express's default HTML 404 page. Added generic error handler to prevent stack trace leakage in production responses.
1 parent e2378d8 commit af8756b

1 file changed

Lines changed: 11 additions & 0 deletions

File tree

src/index.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,17 @@ app.get('/health', (req, res) => {
6565
res.status(200).json({ status: 'ok' });
6666
});
6767

68+
// 404 handler — return JSON for unknown routes
69+
app.use((req, res) => {
70+
res.status(404).json({ error: 'Not found', path: req.path });
71+
});
72+
73+
// Generic error handler — never leak stack traces
74+
app.use((err, req, res, next) => {
75+
console.error('Unhandled error:', err);
76+
res.status(500).json({ error: 'Internal server error' });
77+
});
78+
6879
function heavyComputation(iterations) {
6980
let sum = 0;
7081
for (let i = 0; i < iterations; i++) {

0 commit comments

Comments
 (0)