Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // custom erroe message showing class extending building Error class
- class AppError extends Error {
- public statusCode: number;
- constructor(statusCode: number, message: string, stack = '') {
- super(message);
- this.statusCode = statusCode;
- if (stack) {
- this.stack = stack;
- } else {
- Error.captureStackTrace(this, this.constructor);
- }
- }
- }
- // use of custom error message in pre hook
- // check if the department does not exist
- academicDepartmentSchema.pre('findOneAndUpdate', async function (next) {
- const query = this.getQuery();
- // console.log(query);
- const isDepartmentExist = await AcademicDepartment.findOne(query);
- if (!isDepartmentExist) {
- throw new AppError(404, 'This department does not exists');
- }
- next();
- });
- // ===========================================
- // Gloabal Error Handler
- const handlerGlobalError = (
- err: any,
- req: Request,
- res: Response,
- next: NextFunction,
- ) => {
- const statusCode = err.statusCode || 500;
- const message = err.message || 'Something went wrong!';
- return res.status(statusCode).json({
- success: false,
- message,
- error: err,
- });
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement