Created
June 8, 2024 02:15
-
-
Save TrejoCode/74bebee4ad17a678c99076b4e6714255 to your computer and use it in GitHub Desktop.
Middleware Express Errors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @description Error middleware for handling errors in the application | |
* and converting them to a standard format for the client to consume | |
* and understand the error | |
*/ | |
import type { | |
ErrorRequestHandler, | |
Response, | |
Request, | |
NextFunction, | |
} from 'express' | |
import { ErrorInstance } from '@/config/error' | |
/** | |
* Middleware para manejar errores de recurso no encontrado(404) | |
* Funciona como una routa más, por ello se ejecuta al final de todas las rutas | |
*/ | |
export const errorNotFound = ( | |
_req: Request, | |
_res: Response, | |
next: NextFunction | |
) => { | |
next(new ErrorInstance(404, 'Resource not found')) | |
} | |
/** | |
* @description Middleware para convertir errores a un formato estandarizado, utiliza todos los parametros para un middleware de error | |
* Las funciones de manejo de errores tienen cuatro argumentos en lugar de tres: (err, req, res, next) | |
* next(error) llama al siguiente middleware en la pila de ejecución del server.ts | |
*/ | |
export const errorConverter: ErrorRequestHandler = (err, _req, _res, next) => { | |
let error: ErrorInstance | |
if (!(err instanceof ErrorInstance)) { | |
const errorMessage = err.message || 'Internal server error' | |
error = new ErrorInstance(500, errorMessage, err?.stack) | |
} else { | |
error = err | |
} | |
next(error) | |
} | |
/** | |
* @description Middleware para manejar errores en la aplicación y convertirlos a un formato estandarizado para que el cliente y en desarrollo listar el detalle del error | |
*/ | |
// eslint-disable-next-line @typescript-eslint/no-unused-vars | |
export const errorHandler: ErrorRequestHandler = (err, req, res, _next) => { | |
const { statusCode, message, stack } = err | |
const response = { | |
message, | |
code: statusCode, | |
url: req.originalUrl, | |
} | |
console.error({ ...response, stack }) | |
res.status(statusCode || 500).json(response) | |
} | |
export const asyncErrorBoundary = ( | |
fn: (req: Request, res: Response, next: NextFunction) => Promise<void> | |
) => { | |
return (req: Request, res: Response, next: NextFunction) => { | |
Promise.resolve(fn(req, res, next)).catch((error) => next(error)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment