[QOTD-18] Implement global error-handling middleware
Add src/middleware/error.ts with a four-argument Express error handler
that logs errors server-side via console.error and responds with HTTP
500 and a generic { error: 'Internal server error' } body, never
leaking stack traces to the client. Register it last in a new
src/server.ts entry point.
This commit is contained in:
parent
829bd6d5d8
commit
75a022a372
11
src/middleware/error.ts
Normal file
11
src/middleware/error.ts
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
import type { NextFunction, Request, Response } from 'express';
|
||||||
|
|
||||||
|
export function errorHandler(
|
||||||
|
err: unknown,
|
||||||
|
_req: Request,
|
||||||
|
res: Response,
|
||||||
|
_next: NextFunction
|
||||||
|
): void {
|
||||||
|
console.error(err);
|
||||||
|
res.status(500).json({ error: 'Internal server error' });
|
||||||
|
}
|
||||||
10
src/server.ts
Normal file
10
src/server.ts
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
import express from 'express';
|
||||||
|
import { errorHandler } from './middleware/error';
|
||||||
|
|
||||||
|
const app = express();
|
||||||
|
|
||||||
|
app.use(express.json());
|
||||||
|
|
||||||
|
app.use(errorHandler);
|
||||||
|
|
||||||
|
export default app;
|
||||||
Loading…
Reference in New Issue
Block a user