Today we will check how we can do error handling in Lightning Web Components (LWC). For this, we will create a utility method. Check my previous post for how we can share JavaScript code in Lightning Web Components and create a utility method. We will also use the Custom alert notification component to display the error messages.
ErrorHandling Utility
So first we will create a utility method. In LWC we get different types of errors. And it will be hard to parse them every time we are catching the exception. In this utility method, we will pass the standard error object and will parse that to get the proper error message. Below is the error format which we get when we call the apex method.
/**
* 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 (error.body.duplicateResults && error.body.duplicateResults.length > 0) {
return error.body.duplicateResults.map((e) => e.message);
}
else if (error.body.fieldErrors && error.body.fieldErrors.length > 0 && Array.isArray(error.body.fieldErrors)) {
return error.body.fieldErrors.map((e) => e.message);
}
else if (error.body.pageErrors && error.body.pageErrors.length > 0 && Array.isArray(error.body.pageErrors)) {
return error.body.pageErrors.map((e) => e.message);
}
else if (Array.isArray(error.body)) {
return error.body.map((e) => e.message);
}
// 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)
);
}
Here we are parsing the error message based on different types of error messages we received from the controller.
Error Handling in Lightning Web Components Demo
So now we will create a demo component. For demo purposes, we will create multiple methods and throw an error message.
Below is the code we have used for demo purposes. Here we are simply calling the apex and generating different types of exceptions.
demoCode.html
<template>
<c-lwc-custom-toast></c-lwc-custom-toast>
<lightning-card title="Error Handling in Lightning Web Components">
<div slot="actions">
<lightning-button label="First Error" onclick={firstError}></lightning-button>
<lightning-button label="Second Error" onclick={secondError}></lightning-button>
<lightning-button label="Third Error" onclick={thirdError}></lightning-button>
<lightning-button label="Fourth Error" onclick={fourthError}></lightning-button>
</div>
</lightning-card>
</template>
demoCode.js
import { LightningElement } from 'lwc';
import { reduceErrors } from 'c/lwcUtility';
import listMoreRowError from "@salesforce/apex/LwcErrorParseDemo.listMoreRowError";
import fieldReferenceError from "@salesforce/apex/LwcErrorParseDemo.fieldReferenceError";
import sameFieldMultipleError from "@salesforce/apex/LwcErrorParseDemo.sameFieldMultipleError";
import dmlErrors from "@salesforce/apex/LwcErrorParseDemo.dmlError";
export default class Democode extends LightningElement {
firstError() {
listMoreRowError()
.then(result => {
console.log(result);
})
.catch(error => {
console.log(error);
this.showCustomNotice('Error', reduceErrors(error), 'error');
});
}
secondError() {
fieldReferenceError()
.then(result => {
console.log(result);
})
.catch(error => {
console.log(error);
this.showCustomNotice('Error', reduceErrors(error), 'error');
});
}
thirdError() {
sameFieldMultipleError()
.then(result => {
console.log(result);
})
.catch(error => {
console.log(error);
this.showCustomNotice('Error', reduceErrors(error), 'error');
});
}
fourthError() {
dmlErrors()
.then(result => {
console.log(result);
})
.catch(error => {
console.log(error);
this.showCustomNotice('Error', reduceErrors(error), 'error');
});
}
showCustomNotice(title, message, variant) {
//Here we are calling child component method
this.template.querySelector('c-lwc-custom-toast').updateDetails(title, message, variant);
this.template.querySelector('c-lwc-custom-toast').showCustomNotice();
}
}
As we can see in the demo we can easily parse different error messages. Firstly we will import the errorParse method. Secondly, we will pass the error object in that method as a parameter, and in response, we will get an error message array.
Check my Instagram Page for more updates.
So you can use this utility to catch and display error messages. Did you like this post or have any questions, let me know in the comments. Happy Programming 🙂