All files / src/utils errorHandler.ts

78.94% Statements 30/38
50% Branches 17/34
100% Functions 3/3
77.14% Lines 27/35

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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 561x 1x 1x 1x     64x 64x 64x 64x 64x     1x   64x 59x   64x     64x     64x 12x   64x 64x     1x 64x 48x   64x     64x     64x       64x     64x         64x    
import {isString} from "lodash";
import errorMessages from "./errorMessages";
let {errorParsingData, requestBodyIsInvalid} = errorMessages
export const getErrorObj = async (err: {message: string} | any, code: string | number): Promise<{
    statusCode: number; errorString: string;
}> => {
    let errorCodeResponse = handleErrorCode(code, err)
    err = errorCodeResponse.err
    code = errorCodeResponse.code
    err = handleErrorMessage(code, err)
    return {statusCode: code, errorString: err}
}
 
export const handleErrorCode = (code: string | number, err: string | any,) => {
    // Error if loopback throws NotFoundError
    if (err.code) {
        code = err.code
    }
    Iif (err.sqlMessage) {
        err = err.sqlMessage
    }
    Iif (err.toString().includes("NotFoundError")) {
        code = 404
    }
    if (code == "VALIDATION_FAILED") {
        err = errorMessages.requestBodyIsInvalid
    }
    code = isString(code) ? 422 : code
    return {code, err}
 
}
export const handleErrorMessage = (code: string | number, err: any) => {
    if (err.message) {
        err = err.message
    }
    Iif (err.toString().includes("ER_DATA_TOO_LONG")) {
        err = errorMessages.inputValueIsTooLong
    }
    Iif (err.toString().includes("ER_PARSE_ERROR" || "ER_SP_UNDECLARED_VAR")) {
        err = errorParsingData
    }
    Iif (err.toString().includes("ER_BAD_FIELD_ERROR")) {
        err = err.sqlMessage
    }
 
    Iif (err.toString().includes("UnprocessableEntityError")) {
        err = requestBodyIsInvalid
    }
    Iif (err.message && err.message.toString().includes("Details:")) {
        let validationDetails = err.message.toString().split("Details:") ?? []
        err = validationDetails[1] ?? err
    }
 
    return err
}