Advertisement
sifurr

Custom Error message with status code

Jun 9th, 2024
841
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // custom erroe message showing class extending building Error class
  2. class AppError extends Error {
  3.   public statusCode: number;
  4.  
  5.   constructor(statusCode: number, message: string, stack = '') {
  6.     super(message);
  7.     this.statusCode = statusCode;
  8.  
  9.     if (stack) {
  10.       this.stack = stack;
  11.     } else {
  12.       Error.captureStackTrace(this, this.constructor);
  13.     }
  14.   }
  15. }
  16.  
  17.  
  18. // use of custom error message in pre hook
  19. // check if the department does not exist
  20. academicDepartmentSchema.pre('findOneAndUpdate', async function (next) {
  21.   const query = this.getQuery();
  22.   // console.log(query);
  23.  
  24.   const isDepartmentExist = await AcademicDepartment.findOne(query);
  25.  
  26.   if (!isDepartmentExist) {
  27.     throw new AppError(404, 'This department does not exists');
  28.   }
  29.   next();
  30. });
  31.  
  32.  
  33. // ===========================================
  34.  
  35. // Gloabal Error Handler
  36.  
  37. const handlerGlobalError = (
  38.   err: any,
  39.   req: Request,
  40.   res: Response,
  41.   next: NextFunction,
  42. ) => {
  43.   const statusCode = err.statusCode || 500;
  44.   const message = err.message || 'Something went wrong!';
  45.  
  46.   return res.status(statusCode).json({
  47.     success: false,
  48.     message,
  49.     error: err,
  50.   });
  51. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement