Define a base AppError class with a status code and error code, then subclass it for specific errors (NotFoundError, ValidationError, UnauthorizedError). Register a global error-handling middleware in Express (or exception filter in NestJS) that catches everything, logs it, and returns a consistent error response shape:
`class AppError extends Error {
constructor(
public message: string,
public statusCode: number,
public code: string
) { super(message); }
}
// Global handler
app.use((err, req, res, next) => {
if (err instanceof AppError) {
return res.status(err.statusCode).json({ error: err.code, message: err.message });
}
// Unexpected error
logger.error(err);
res.status(500).json({ error: 'INTERNAL_ERROR' });
});`
Top comments (0)