Snai3i-LandingPage-FormBuilder / backend / src / middlewares / errorMiddleware.ts
errorMiddleware.ts
Raw
import { HttpCodes } from "../config/errors";
import ErrorHandler from "../utils/errorHandler";
import { InDev } from "../config/env";
import { Request,Response, NextFunction } from "express";

export function errorMiddleware(err: ErrorHandler, req: Request, res: Response, next: NextFunction) {
	const status = err.statusCode || HttpCodes.InternalServerError.code;
	let message = err.message || HttpCodes.InternalServerError.message;
	const errorDetails = InDev ? err : undefined;

 // wrong mongoose object id error
 if (err.name === 'CastError') {
    message = `Resource not found.`;
  }

  // wrong jwt error
  if (err.name === 'JsonWebTokenError') {
    message = 'JSON Web Token is invalid. Try Again!!!';
  }

  // wrong jwt expired error
  if (err.name === 'TokenExpiredError') {
    message = 'JSON Web Token is expired. Try Again!!!';
  }

	res.status(status).json({
		status,
		message,
		error: errorDetails,
	});
}