Exception Handling in Salesforce Flow

Your flow may fail if it includes an element that interacts with the Salesforce database, such as an Update Records element, or a Submit for Approval core action. How do you handle errors in Salesforce Flow?

In this article, I’ll go over some exception handling techniques for both screen flow and auto-launched flow.

Advertisements

✷ What happens when a Flow fails?

When a flow fails, the user who is running it receives this error message.

An unhandled fault has occurred in this flow
An unhandled fault has occurred while processing 
the flow. Please contact your system administrator 
for more information.

The running user is unable to continue with the flow or return to a previous section of the flow. A fault email is sent to the admin who created the flow. The email describes the failed element, the error message, and which elements were executed during the failed interview.

Error element Assign_fields_values (FlowAssignment).
Flow encountered an error when processing and converting between data types. Please check the flow and ensure all data types are matched correctly.

The above flow error message indicates that an assignment element was used to insert a value into a field, but the values were not assigned based on the data type of the field. For example, you are not putting the correct record ID in the lookup field.

An error occurred at element Delete_1.
DELETE --- There is nothing in Salesforce matching your 
delete criteria.

In the preceding example, a Delete Record element in a Flow causes an error if no records matching the selection criteria are found.

↠ Salesforce publishes a Flow Execution Error Event platform event message for screen flows.

☞ How to handle errors in Screen Flow ?

To change the default behavior of flow failures, we can use fault paths for all elements that can fail. We can deal with the error and do the following in the fault path.

Fault path
  • Add a screen element and display the flow failure message to the user.
  • Create a record in your custom Error Log object.
  • Send yourself an email in case of failure.

See how the exception in the screen flow can be handled in the video down below.

Advertisements

☞ How to handle errors in Auto-launched Flow?

Salesforce does not publish Flow Execution Error Event platform event message in case of any exception in auto-launched flow. So, in order to display the user-friendly message to the user and to create an object record for the error log, we will use a custom platform event.

Create a platform event in your org.

  • Enter Label and Plural label
  • In Publish Behaviour field select ‘Publish Immediately
  • Click on Save.

Create a field to store the error message.

Check out the video below to see how the exception in the auto-lanched flow can be handled.

Advertisements

The custom exception class and LWC code are listed below.

errorMessage.js

import { LightningElement,api } from 'lwc';
import { subscribe, unsubscribe, onError, setDebugFlag, isEmpEnabled } from 'lightning/empApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class ErrorMessage extends LightningElement {
subscription = {};
@api channelName = '/event/Flow_Error__e';
// connected callback : initialise
connectedCallback() {
// Register error listener
this.registerErrorListener();
this.handlePESubscribe();
}
handlePESubscribe() {
// Callback invoked whenever a new platfrom event message is created.
const thisReference = this;
const messageCallback = function(response) {
var obj = JSON.parse(JSON.stringify(response));
//simplify the flow failure error message
let error_message = obj.data.payload.Error_Message_Text__c.substring(0, obj.data.payload.Error_Message_Text__c.indexOf("You can look up ExceptionCode values"));
console.log('Simplified error: '+ error_message);
//show toast message
const evt = new ShowToastEvent({
title: 'Error !',
message: error_message,
variant: 'error',
mode:'sticky'
});
thisReference.dispatchEvent(evt);
};
// Invoke subscribe method of empApi. Pass reference to messageCallback
subscribe(this.channelName, -1, messageCallback).then(response => {
// Response contains the subscription information on subscribe call
console.log('Subscription request sent to: ', JSON.stringify(response.channel));
this.subscription = response;
});
}
/* If you want to unsubscribe use this channel.
handleUnsubscribe() {
// Invoke unsubscribe method of empApi
unsubscribe(this.subscription, response => {
console.log('unsubscribe method response: ', JSON.stringify(response));
});
}
*/
// Error listner method
registerErrorListener() {
onError(error => {
// Error contains the server-side error
console.log('Error received: ', JSON.stringify(error));
});
}
}
view raw errorMessage.js hosted with ❤ by GitHub

errorMessage.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata"&gt;
<apiVersion>55.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordPage</target>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
</targets>
<targetConfigs>
<targetConfig targets="lightning__RecordPage, lightning__AppPage, lightning__HomePage">
<property name="channelName" type="String" />
</targetConfig>
</targetConfigs>
</LightningComponentBundle>

ExceptionUtilityCls.cls

public with sharing class ExceptionUtilityCls {
public class CustomException extends Exception{}
@invocableMethod(label='Custom Exception' description='Invoke custom eception method.' category='Exception Handling')
public static void throwCustomException(List<String> exceptionMessage) {
throw new CustomException('Exception hac occured in the process /flow '+
'Please contact your system adminstrator : '+ exceptionMessage[0] );
}
}

Summary

It is always a good idea to deal with exceptions in code; the same stands true for flow. The best course of action is to plan ahead for exception/errors and incorporate proper fault handling into your flow design, which will help you handle errors more effectively when they do happen.

Join 242 other subscribers
Advertisements
Advertisements
  • Streamline User Access Management with New “View Summary” Feature
    Salesforce admins, rejoice! The Summer ’24 release introduces a “View Summary” button on user detail page, providing a centralized summary of user permissions including user, object, field, custom permissions, group, and queue memberships. This feature streamlines troubleshooting, enhances security reviews, empowers admins, and supports organizational governance. Admins can prepare for the release and anticipate improved management of user permissions.
  • New Automation Lightning App – Streamlining Your Flows
    In the upcoming Summer’24 release, Salesforce will introduce the Automation Lightning app, designed to improve flow management for Trailblazers. It offers seamless creation, management, and collaboration on Salesforce Flow automations. Key features include enhanced search, collaboration, and recently viewed flows, accessible through the App Launcher by enabling the app in Process Automation Settings.
  • Automate Every Stage of Your File Management in Salesforce
    The digital revolution demands efficient file management. Salesforce automation minimizes errors and enhances productivity. Salesforce offers diverse file management features and integrates with Titan Files for enhanced functionality. Titan Files facilitates automated file transfers, document management, and Salesforce integration without the need for coding. It also provides virus scanning, image modification, and OCR capabilities.

Arun Kumar

Arun Kumar is a Salesforce Certified Platform Developer I with over 7+ years of experience working on the Salesforce platform. He specializes in developing custom applications, integrations, and reports to help customers streamline their business processes. Arun is passionate about helping businesses leverage the power of Salesforce to achieve their goals.

This Post Has 2 Comments

  1. dummy

    For Throw Exception –> can’t we just use the Rollback Elements ?

    1. Arun Kumar

      Hi,

      The element “Rollback Back Records” is currently only available in the Screen flow.

      Thanks

Leave a Reply