Errors from Salesforce backend needs to be shown properly in custom LWC components. Salesforce provides a reduceErrors function with which different error types and sources from Salesforce backend are filtered correctly
reduceErrors can be found here: lwc-recipes/force-app/main/default/lwc/ldsUtils at main · trailheadapps/lwc-recipes
Both the reduceErrors and modified showToast could be implemented in customer org for centralised and easy usage. No need to duplicated functions in every component.
Example usage to show errors from Salesforce backend in LWC component
Import functions from lwcUtils (or name of JS file in customer org)
import { reduceErrors, showToast } from "c/lwcUtils";
Example function
async handleUploadFinished(event) { try { // Do something that potentially throws error } catch (error) { showToast(this, "Something went wrong", reduceErrors(error), "error"); } } }
The showToast function takes as argument the context, title, the filtered error messages, the type of toast and optionally the mode of the toast, see Salesforce Developers
showToast with reduceErrors function
/** * Method for showing toast messages in LWC components. * @param {object} context * @param {string} title The title of the toast, displayed as a heading. * @param {(string | string[])} messages A string (or array of strings) containing a message for the user. * @param {string} variant The theme and icon displayed in the toast * @param {string} mode Determines how persistent the toast is * @see https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.use_toast */export function showToast(context, title, messages, variant, mode) { context.dispatchEvent( new ShowToastEvent({ title, message: messages, variant, mode, }) );}
Use same function to throw messages from frontend, example
showToast(this, "Deleted", "File was deleted", "success");

Leave a comment