Import the existing local project snapshot. This commit organizes existing files; it does not represent newly developed functionality.
34 lines
916 B
TypeScript
34 lines
916 B
TypeScript
import type { ErrorRequestHandler } from 'express';
|
|
import { ZodError } from 'zod';
|
|
|
|
export class HttpError extends Error {
|
|
status: number;
|
|
code: string;
|
|
|
|
constructor(status: number, code: string, message: string) {
|
|
super(message);
|
|
this.status = status;
|
|
this.code = code;
|
|
}
|
|
}
|
|
|
|
export const notFoundHandler = () => {
|
|
throw new HttpError(404, 'NOT_FOUND', 'Not found');
|
|
};
|
|
|
|
export const errorHandler: ErrorRequestHandler = (err, _req, res, _next) => {
|
|
if (err instanceof ZodError) {
|
|
res.status(400).json({
|
|
error: 'Validation failed',
|
|
code: 'VALIDATION_ERROR',
|
|
details: err.flatten(),
|
|
});
|
|
return;
|
|
}
|
|
|
|
const status = err instanceof HttpError ? err.status : 500;
|
|
const code = err instanceof HttpError ? err.code : 'INTERNAL_ERROR';
|
|
const message = status === 500 ? 'Internal server error' : err.message;
|
|
res.status(status).json({ error: message, code });
|
|
};
|