All files / src/utils handle_error.ts

73.33% Statements 11/15
83.33% Branches 10/12
83.33% Functions 5/6
76.92% Lines 10/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 37 38            7x 10x     7x     10x 10x         7x 10x             10x 10x         10x        
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,
            value: err.errors[field].value
        }));
        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,
            value: error.value
        }));
        res.status(400).json({ message: err.message, errors });
    } else E{
        res.status(500).json({ message: err.message });
    }
};