All files / src/utils handle_error.ts

80% Statements 12/15
91.66% Branches 11/12
83.33% Functions 5/6
84.61% Lines 11/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36            8x 11x     8x     11x 10x         8x 11x           11x 10x       10x   1x    
import { Response } from 'express';
import {ValidationError} from "types/validation_errors";
import mongoose from "mongoose";
import * as expressValidator from "express-validator";
 
 
export const isMongoValidationErrors = (err: any) => {
    return err instanceof mongoose.Error.ValidationError;
}
 
export const isReqValidationErrors = (err: any): err is {
    message: any; errors: expressValidator.ValidationError[]
} => {
    return Array.isArray(err.errors) && err.errors.every((error: any) => {
        return typeof (error.param === 'string' || error.path === 'string') && typeof error.msg === 'string';
    });
};
 
 
export const handleError = (err: any, res: Response) => {
    Iif (isMongoValidationErrors(err)) {
        const errors: ValidationError[] = Object.keys(err.errors).map(field => ({
            field,
            message: err.errors[field].message
        }));
        res.status(400).json({ message: err.message, errors });
    } else if (isReqValidationErrors(err)) {
        const errors: ValidationError[] = err.errors.map((error: any) => ({
            field: error.parm ?? error.path ,
            message: error.msg
        }));
        res.status(400).json({ message: err.message, errors });
    } else {
        res.status(500).json({ message: err.message });
    }
};