Home > Mobile >  Build a re-usable error message convertor
Build a re-usable error message convertor

Time:08-24

I work on a project where we receive error messages from the backend. Sometimes the error messages are not frontend friendly. We are doing some work to tidy these up, but in the meantime I created a function that takes the error message and replaces any values.

I want to make the function re-usable for other error messages and wondered if anyone has any advice.

Here is the function with 1 error message currently.

Error message entered: 'Minimum payment_amount is $10.' Error message being returned: 'Minimum payment amount is $10.'

    const errorMessageConvertor = (errorMessage) => {
    if (errorMessage !== undefined) {
        const convertedErrorMessage = errorMessage.toString();
        return convertedErrorMessage.replace("payment_amount", "payment amount");
    }
};

CodePudding user response:

If you only want to get rid of underscores then this should solve the problem, it will replace all the underscores with spaces.

const errorMessageConvertor = (errorMessage) => {
    if (errorMessage !== undefined) {
        const convertedErrorMessage = errorMessage.toString();
        return convertedErrorMessage.replaceAll('_', ' ');
    }
};

CodePudding user response:

Maybe something like that

    const errorMessageConvertor = (errorMessage, keyToReplace, valueToReplace) => {
    if (errorMessage !== undefined) {
        const convertedErrorMessage = errorMessage.toString();
        return convertedErrorMessage.replace(keyToReplace, valueToReplace);
    }
};

// usage 
errorMessageConvertor('Minimum payment_amount is $10.','payment_amount','payment amount')

  • Related