1

I'm doing a callout from my LWC js controller to an @AuraEnabled method in my Apex controller. It works successfully but I also need to handle errors. I added temporary code throw an Exception in the controller method to test error handling. I coded the JS draft below to check what info I get back. The members of "error" are all undefined. The alert shows "undefined - undefined - undefined". Any clue how to get info on the error that occured?

        import myApexMethod from '@salesforce/apex/myApexClass.myApexMethod';
...
        myApexMethod({ param1 : param1Value,
                       param2 : param2Value, 
                       param3 : param3Value})
        .then(result => {
            alert('did apex call.');
        })
        .catch(error => {
            alert(error.name + ' - ' + error.message + ' - ' + error.stack);
        });

2 Answers 2

3

The lwc-recipes repo, provided by Salesforce, provides a function you can use in any of your projects to parse the exceptions properly. I've included it here for reference. You can check out the repo for examples of how it's used in various types of components.

/**
 * Reduces one or more LDS errors into a string[] of error messages.
 * @param {FetchResponse|FetchResponse[]} errors
 * @return {String[]} Error messages
 */
export function reduceErrors(errors) {
    if (!Array.isArray(errors)) {
        errors = [errors];
    }

    return (
        errors
            // Remove null/undefined items
            .filter((error) => !!error)
            // Extract an error message
            .map((error) => {
                // UI API read errors
                if (Array.isArray(error.body)) {
                    return error.body.map((e) => e.message);
                }
                // Page level errors
                else if (
                    error?.body?.pageErrors &&
                    error.body.pageErrors.length > 0
                ) {
                    return error.body.pageErrors.map((e) => e.message);
                }
                // Field level errors
                else if (
                    error?.body?.fieldErrors &&
                    Object.keys(error.body.fieldErrors).length > 0
                ) {
                    const fieldErrors = [];
                    Object.values(error.body.fieldErrors).forEach(
                        (errorArray) => {
                            fieldErrors.push(
                                ...errorArray.map((e) => e.message)
                            );
                        }
                    );
                    return fieldErrors;
                }
                // UI API DML page level errors
                else if (
                    error?.body?.output?.errors &&
                    error.body.output.errors.length > 0
                ) {
                    return error.body.output.errors.map((e) => e.message);
                }
                // UI API DML field level errors
                else if (
                    error?.body?.output?.fieldErrors &&
                    Object.keys(error.body.output.fieldErrors).length > 0
                ) {
                    const fieldErrors = [];
                    Object.values(error.body.output.fieldErrors).forEach(
                        (errorArray) => {
                            fieldErrors.push(
                                ...errorArray.map((e) => e.message)
                            );
                        }
                    );
                    return fieldErrors;
                }
                // UI API DML, Apex and network errors
                else if (error.body && typeof error.body.message === 'string') {
                    return error.body.message;
                }
                // JS errors
                else if (typeof error.message === 'string') {
                    return error.message;
                }
                // Unknown error shape so try HTTP status text
                return error.statusText;
            })
            // Flatten
            .reduce((prev, curr) => prev.concat(curr), [])
            // Remove empty strings
            .filter((message) => !!message)
    );
}
2

I added--

alert(JSON.stringify(error));

and that gave me the info I need; see image below.

Changed my code to --

alert('Error members -- ' + error.status + ' - ' + error.body.message + ' - ' + error.body.stackTrace);

enter image description here

1
  • 1
    Screenshots are not accessible to those people who use screen readers and other assistive technology. We would prefer to have the response in text so that it is widely accessible. Instead of using alert, use console.log or console.error so you can copy the plain text.
    – sfdcfox
    Dec 6, 2023 at 15:12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .