Skip to content

Commit

Permalink
feat: error handler middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
JoseAlbDR committed Mar 27, 2024
1 parent ce141e7 commit b833dbe
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
42 changes: 42 additions & 0 deletions src/presentation/middlewares/error-handler.middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { NextFunction, Request, Response } from 'express';

import { CustomAPIError } from '../../domain/errors';
import { HttpCodes } from '../../config/http-status-codes.adapter';
import { MulterError } from 'multer';

/**
* Middleware class for handling errors.
*/
export class ErrorHandlerMiddleware {
/**
* Handles errors and sends appropriate responses.
*/
static handle(err: Error, _req: Request, res: Response, _next: NextFunction) {
console.log({ err });

let message, statusCode;

// Handle unknown errors
if (!err || err === null) {
statusCode = 500;
message = 'Unknown error';
}

// Handle CustomAPIError
if (err instanceof CustomAPIError) {
statusCode = err.statusCode;
message = err.message;
}

// Handle MulterError
if (err instanceof MulterError) {
statusCode = HttpCodes.BAD_REQUEST;
message = err.message;
}

return res.status(statusCode || HttpCodes.INTERNAL_SERVER_ERROR).json({
name: err?.name || 'Error',
message: message || err?.message,
});
}
}
4 changes: 4 additions & 0 deletions src/presentation/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import 'express-async-errors';
import express, { Router } from 'express';
import cors from 'cors';
import morgan from 'morgan';
import { ErrorHandlerMiddleware } from './middlewares/error-handler.middleware';

interface Options {
port: number;
Expand Down Expand Up @@ -33,6 +34,9 @@ export class Server {

this.app.use(this.routes);

//* Error Handler Middleware
this.app.use(ErrorHandlerMiddleware.handle);

this.serverListener = this.app.listen(this.port, async () => {
try {
console.log(`Server running on port ${this.port}`);
Expand Down

0 comments on commit b833dbe

Please sign in to comment.