refractor code,

This commit is contained in:
root
2026-05-21 12:35:49 -04:00
parent e74681e810
commit f009ca10c6
158 changed files with 215801 additions and 5884 deletions
@@ -0,0 +1,29 @@
import { Request, Response, NextFunction } from 'express'
import { AppError } from './index'
export function errorMiddleware(err: any, _req: Request, res: Response, _next: NextFunction) {
if (err.name === 'ZodError') {
return res.status(400).json({ error: 'validation_error', message: 'Invalid request body', issues: err.issues, statusCode: 400 })
}
if (err.code === 'P2025') {
return res.status(404).json({ error: 'not_found', message: 'Resource not found', statusCode: 404 })
}
if (err.code === 'P2002') {
return res.status(409).json({ error: 'conflict', message: 'A resource with this value already exists', statusCode: 409 })
}
if (err instanceof AppError) {
if (err.statusCode >= 500) console.error('[API Error]', err)
return res.status(err.statusCode).json({ error: err.error, message: err.message, statusCode: err.statusCode, ...err.data })
}
const statusCode = err.statusCode ?? 500
const message = err.message ?? 'Internal server error'
const code = err.code ?? 'internal_error'
if (statusCode >= 500) console.error('[API Error]', err)
res.status(statusCode).json({ error: code, message, statusCode })
}
+43
View File
@@ -0,0 +1,43 @@
export class AppError extends Error {
readonly statusCode: number
readonly error: string
readonly data?: Record<string, unknown>
constructor(message: string, statusCode: number, error: string, data?: Record<string, unknown>) {
super(message)
this.statusCode = statusCode
this.error = error
this.data = data
this.name = this.constructor.name
}
}
export class ValidationError extends AppError {
constructor(message = 'Validation error') {
super(message, 400, 'validation_error')
}
}
export class NotFoundError extends AppError {
constructor(message = 'Resource not found') {
super(message, 404, 'not_found')
}
}
export class ConflictError extends AppError {
constructor(message = 'A resource with this value already exists') {
super(message, 409, 'conflict')
}
}
export class ForbiddenError extends AppError {
constructor(message = 'Forbidden') {
super(message, 403, 'forbidden')
}
}
export class UnauthorizedError extends AppError {
constructor(message = 'Unauthorized') {
super(message, 401, 'unauthorized')
}
}