Thursday, 16 February 2023

How to handle mongoose errors globaly

As for now, I'm using mongoose middleware to handle Mongoose specific errors (validation, cast, ....).
I'm using the following code in all of my schemas:

schema.post('save', handleValidationError);
schema.post('findOneAndUpdate', handleValidationError);
schema.post(['findOne', 'deleteOne'], handleCastError);

Is there anyway to make this global in all schemas without repeating the code?
I tried to use plugins as the following but they don't get triggered if an error happens.

const errorsPlugin = (schema: any, _options: any): void => {
    schema.post('save', handleValidationError);
    schema.post('findOneAndUpdate', handleValidationError);
    schema.post(['findOne', 'deleteOne'], handleCastError);
};

const connection = await mongoConnect(url);
plugin(errorsPlugin);
logger.info(`MongoDB connected: ${connection.connection.name}`);


from How to handle mongoose errors globaly

No comments:

Post a Comment