SlideShare a Scribd company logo
Custom Lightning
Components Error
Handling
​ Head of Salesforce Engineering, Provar
• Developing Salesforce.com relationship
• Defining Salesforce integration roadmap
• Accelerate new development
• Increase functional coverage
• SFDC SME
​
​ Background
• 10y Salesforce.com
• 3x DF speaker
• 5 AppExchange & 3 ISV Apps
• Co-organiser London SF Developer’s Meetup
• Former CTO makepositive & Brightgen
• 2x former Provar customer!
Richard Clark
Twitter/LinkedIn: @RichClark808
http://provartesting.com
About Me
About Provar
Point and click test
creation
Runs UI and API
steps in the same test
Highly maintainable test
cases
Aligned to the
Salesforce roadmap
Provar is the only automated testing tool for Salesforce.
@Provar
http://ProvarTesting.com
References… (eh, already?)
Independent Blogs/Forums
1. How to Handle Apex Errors for
Lightning
2. Exception Handling in Lightning
3. Testing AuraHandledExceptions
4. Lightning Error Handler
5. Best practice catching errors in
Lightning
Official Salesforce
1. Throwing & Handling Errors
2. Set an Error Response
3. ui:inputDefaultError
4. Validating Fields
5. Returning Errors from Apex
6. Validating Fields
7. lightning:notificationsLibrary
8. Lightning Messaging Framework
1. Todd’s Browser Dev Tool Debugging like a Unicorn-Ninja-Cat-Rockstar
2. debugger keyword
3. Lightning Chrome Extension
4. Setup -> Lightning Components -> Enable Debug Mode ?
5. Refresh page, refresh page, refresh page and refresh page...
Lesson 1 - Debugging...
<lightning:input aura:id="contactField" name="firstName"
label="First Name" value="{!v.simpleNewContact.FirstName}"
required="true"/>
<lightning:input aura:id="contactField" type="phone"
name="phone" label="Phone"
pattern="^(1?(-?d{3})-?)?(d{3})(-?d{4})$"
messageWhenPatternMismatch="The phone number must contain
7, 10, or 11 digits. Hyphens optional."
value="{!v.simpleNewContact.Phone}" required="true"/>
Question: Which of these enforce field validation ?
Demo - Let’s see...
Lesson 2 - Validation is 2 Step!
● Depending on the component library you use:
○ For <ui:inputXXXXX /> use
inputCmp.set("v.errors", [{message:"your msg"}]);
See Validating Fields
○ For <lightning:input/select/textarea > use
inputCmp.showHelpMessageIfInvalid();
Helper:
validateForm: function(component) {
var valid = true;
// Show error messages if field validation fails
var uiValid = component.find('contactField').reduce(
function (validFlds, inCmp) {
inCmp.showHelpMessageIfInvalid();
return validFlds &&
inCmp.get('v.validity').valid;
},
true);
if (uiValid) {
// Do any client side validation e.g. Account isActive
}
return(valid);
}
lightning:input
In your Component Controller:
handleSave: function(comp, evt, hlpr)
{
if (hlpr.validateForm(comp)) {
//do stuff
}
● Public examples rarely handle server errors
○ console.log() and //Do something is not enough!
● Demo: Validation Rule on Contact
● Demo: DML, Server and Dupe Warnings
● Demo: Handling the Validation Rule properly
Lesson 3 - Silent but Deadly...
● Use console.error(); instead of console.log(); unless it’s a warning
● Display something (next lesson)
● response.getState(), has 4 states - deal with them all
a. SUCCESS
b. DRAFT (if using LDS and Local Cache)
c. ERROR
d. INCOMPLETE (offline/session expired)
What does ‘properly’ mean
Lesson 4 - How do you eat yours?
● throw new Error(“Arghhh!”);
● console.log() / console.error()
● <ui:outputText />
● <ui:message ... />
● $A.get("e.force:showToast");
● <lightning:notificationsLibrary/>
● Spring 18: <lightning:messages/> (coming up...)
Consider both desktop and mobile user experiences.
Choose your weapon!
Demo - Anyone for toast ?
showToast vs notificationsLibrary
var resultsToast = $A.get("e.force:showToast");
resultsToast.setParams({
"title": "Contact Saved",
"message": "The new contact was created."
});
resultsToast.fire();
<!-- Component markup -->
<lightning:notificationsLibrary aura:id="notifLib"/>
// JS Controller
component.find('notifLib').showToast({
"variant" : “success”,
"title": "Contact Saved",
"message": "The new contact was created"
});
Spring 18: lightning:messages
● Spring18 (API 42.0)
○ <lightning:messages/>
○ No, it wasn’t in the release notes! See here
○ And it doesn’t appear in ./componentReference/suite.app
○ But it is in other examples in the Lightning Components Dev Guide
Demo (from Spring 18: Interactive Forms article)
○ It avoids silent failures and is ‘plumbing free’
○ Doesn’t (yet) support duplicate warnings
○ Doesn’t provide any message details (s.t. docs)
○ Keep an eye on it for the future, great catch-all for now
● If creating components for LightningOut/Visualforce…
○ UI Validation does work
○ showToast not supported in VF (Classic or LEX)
○ So use ui:outputtext/ui:message
● Make your error handling Environmentally Friendly!
○ What & Why: Lightning Messaging Overview
○ How:
http://bobbuzzard.blogspot.co.uk/2015/11/context-is-everything.html
Lesson 5 - LightningOut
● UI Validation
● Duplicate Rules
● Data Model Validation Rules
● Apex DMLExceptions
● Other Apex Exceptions (e.g. NullPointer, Custom)
● Salesforce Platform Errors/Limits
Recap - Errors to handle
Three areas to check within your JS error handler:
● pageErrors: e.g. Apex Exceptions, Dupe Rules, Validation
● fieldErrors: e.g. Field validation
● potentialDuplicates:* TBC!
Expect multiple errors and display them all (as appropriate).
Lesson 6 - Server Errors
Three areas to check within your JS error handler:
● pageErrors: e.g. Apex Exceptions, Dupe Rules, Validation
● fieldErrors: e.g. Field validation
● potentialDuplicates:* TBC!
Expect multiple errors and display them all (as appropriate).
Lesson 6 - Server Errors
// What does the user see?
Account a = new Account();
insert a; // Whoops, I broke Salesforce?
Lesson 7 - AuraHandledException
Apex Custom Controller method using @AuraEnabled
// What does the user see?
try {
Account a = new Account();
insert a;
}
catch (Exception ex) {
AuraHandledException ahe = new
AuraHandledException(“Unexpected Error:
”+ex.getMessage());
ahe.setMessage(“Err in accCreate:”+ex.getStackTrace());
throw ahe;
}
Lesson 7 - AuraHandledException
Apex Custom Controller method using @AuraEnabled
Demo - AuraHandledException
VS
Lesson 7 (cont’d)
Lightning Components Developer Guide:
“The benefit of throwing AuraHandledException, instead of letting a system exception be
returned, is that you have a chance to handle the exception more gracefully in your client code”
Some quirks to be aware of:
● catch (DMLException) & throw AuraHandledException:
○ message is less readable than throwing DMLException
○ or parse out the ugly message
● catch (Exception) & throw AuraHandledException
○ Avoids “Internal Server Error”
● AuraHandledException.setMessage() for meaningful messages in debug
logs instead of “Script thrown exception”
● Develop your own re-usable custom error component
○ Consistency across your application
○ Single point of change
○ Easy to implement
● Don’t forget i18n for your messages:
○ $A.get(“$Label.c.labelName”);
○ $A.get(“$Label.namespace.labelName”);
● Here’s a useful starting point: Lightning Error Handler plus
<lightning:notificationsLibrary/>
Final Lesson - Error Component
Putting it all together...
Summary
● Learn to debug Lightning
● Refresh/reload page or markup versions
● 2-step UI validation
● Handle all 4 callback states
● Apex AuraHandledException
● Custom reusable error/message component
○ Environment aware
○ Multi-component aware
○ Custom labels
○ Start small
● Spring 18: <lightning:messages/> during dev?
Thank you!Any questions?

More Related Content

PPTX
Integrating SalesforceDX and Test Automation
PDF
Testing lightning components feb 15th 2018
PPTX
Provar webinar 15-03-2018
PPT
Test automation process
PDF
Mastering Test Automation: How to Use Selenium Successfully
PDF
Create an architecture for web test automation
PPTX
Telerik test studio webinar deck
PPTX
Introduction to SoapUI day 1
Integrating SalesforceDX and Test Automation
Testing lightning components feb 15th 2018
Provar webinar 15-03-2018
Test automation process
Mastering Test Automation: How to Use Selenium Successfully
Create an architecture for web test automation
Telerik test studio webinar deck
Introduction to SoapUI day 1

What's hot (20)

DOCX
Katalon studio vs selenium comparision
PDF
Integration testing - A&BP CC
PPS
Final Automation Testing
PPTX
A Look into Automated Web UI Test
PDF
Test Automation Frameworks Using Selenium | Edureka
PDF
selenium meetup sf talk march 2014 Selenium at Scale
PPTX
Level Up Your Salesforce Unit Testing
PDF
Java Test Automation for REST, Web and Mobile
PPTX
Selenium Test Automation
PPTX
Lap Around Visual Studio 2010 Ultimate And TFS 2010
PPTX
Web based automation testing on Node.js environment
PPTX
Execute Automation Testing in 3 Steps
PPTX
Colorful world-of-visual-automation-testing-latest
PPTX
Agile test-management-test-rail-lastest
PPT
Automation With A Tool Demo
PPTX
Automated Testing using JavaScript
PPTX
ProtractorJS for automated testing of Angular 1.x/2.x applications
PPT
Test Automation Framework Designs
PPTX
Automation using Javascript
PPTX
Setup and run automated test framework for android application
Katalon studio vs selenium comparision
Integration testing - A&BP CC
Final Automation Testing
A Look into Automated Web UI Test
Test Automation Frameworks Using Selenium | Edureka
selenium meetup sf talk march 2014 Selenium at Scale
Level Up Your Salesforce Unit Testing
Java Test Automation for REST, Web and Mobile
Selenium Test Automation
Lap Around Visual Studio 2010 Ultimate And TFS 2010
Web based automation testing on Node.js environment
Execute Automation Testing in 3 Steps
Colorful world-of-visual-automation-testing-latest
Agile test-management-test-rail-lastest
Automation With A Tool Demo
Automated Testing using JavaScript
ProtractorJS for automated testing of Angular 1.x/2.x applications
Test Automation Framework Designs
Automation using Javascript
Setup and run automated test framework for android application
Ad

Similar to London SF Developers: Custom Lightning Component Error Handling (20)

PPTX
Lightning page optimization &amp; best practices
PPT
ASP.NET 05 - Exception Handling And Validation Controls
PPTX
Lightning Talk: JavaScript Error Handling
PDF
Apex Enterprise Patterns: Building Strong Foundations
PPT
Error management
PPT
JAX 08 - Agile RCP
PPTX
Frontend training
PPT
PDF
Php exceptions
PPT
Working Effectively With Legacy Code
PDF
AngularJs Style Guide
PDF
PDF
PPT
Stopping the Rot - Putting Legacy C++ Under Test
PPTX
DotNet unit testing training
ODP
WebTest - Efficient Functional Web Testing with HtmlUnit and Beyond
PPT
Ppt lesson 06
PPT
Ppt lesson 06
PPT
Ppt lesson 06
PPTX
Lecture 20-21
Lightning page optimization &amp; best practices
ASP.NET 05 - Exception Handling And Validation Controls
Lightning Talk: JavaScript Error Handling
Apex Enterprise Patterns: Building Strong Foundations
Error management
JAX 08 - Agile RCP
Frontend training
Php exceptions
Working Effectively With Legacy Code
AngularJs Style Guide
Stopping the Rot - Putting Legacy C++ Under Test
DotNet unit testing training
WebTest - Efficient Functional Web Testing with HtmlUnit and Beyond
Ppt lesson 06
Ppt lesson 06
Ppt lesson 06
Lecture 20-21
Ad

Recently uploaded (20)

PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PDF
System and Network Administraation Chapter 3
PDF
Cost to Outsource Software Development in 2025
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PPTX
CHAPTER 2 - PM Management and IT Context
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
Digital Strategies for Manufacturing Companies
PPTX
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
top salesforce developer skills in 2025.pdf
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PPTX
assetexplorer- product-overview - presentation
PPTX
Reimagine Home Health with the Power of Agentic AI​
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PPTX
Why Generative AI is the Future of Content, Code & Creativity?
PPTX
Computer Software and OS of computer science of grade 11.pptx
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PPTX
Transform Your Business with a Software ERP System
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
System and Network Administraation Chapter 3
Cost to Outsource Software Development in 2025
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
CHAPTER 2 - PM Management and IT Context
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
Digital Strategies for Manufacturing Companies
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
Operating system designcfffgfgggggggvggggggggg
top salesforce developer skills in 2025.pdf
Design an Analysis of Algorithms I-SECS-1021-03
assetexplorer- product-overview - presentation
Reimagine Home Health with the Power of Agentic AI​
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Why Generative AI is the Future of Content, Code & Creativity?
Computer Software and OS of computer science of grade 11.pptx
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
How to Choose the Right IT Partner for Your Business in Malaysia
Transform Your Business with a Software ERP System

London SF Developers: Custom Lightning Component Error Handling

  • 2. ​ Head of Salesforce Engineering, Provar • Developing Salesforce.com relationship • Defining Salesforce integration roadmap • Accelerate new development • Increase functional coverage • SFDC SME ​ ​ Background • 10y Salesforce.com • 3x DF speaker • 5 AppExchange & 3 ISV Apps • Co-organiser London SF Developer’s Meetup • Former CTO makepositive & Brightgen • 2x former Provar customer! Richard Clark Twitter/LinkedIn: @RichClark808 http://provartesting.com About Me
  • 3. About Provar Point and click test creation Runs UI and API steps in the same test Highly maintainable test cases Aligned to the Salesforce roadmap Provar is the only automated testing tool for Salesforce. @Provar http://ProvarTesting.com
  • 4. References… (eh, already?) Independent Blogs/Forums 1. How to Handle Apex Errors for Lightning 2. Exception Handling in Lightning 3. Testing AuraHandledExceptions 4. Lightning Error Handler 5. Best practice catching errors in Lightning Official Salesforce 1. Throwing & Handling Errors 2. Set an Error Response 3. ui:inputDefaultError 4. Validating Fields 5. Returning Errors from Apex 6. Validating Fields 7. lightning:notificationsLibrary 8. Lightning Messaging Framework
  • 5. 1. Todd’s Browser Dev Tool Debugging like a Unicorn-Ninja-Cat-Rockstar 2. debugger keyword 3. Lightning Chrome Extension 4. Setup -> Lightning Components -> Enable Debug Mode ? 5. Refresh page, refresh page, refresh page and refresh page... Lesson 1 - Debugging...
  • 6. <lightning:input aura:id="contactField" name="firstName" label="First Name" value="{!v.simpleNewContact.FirstName}" required="true"/> <lightning:input aura:id="contactField" type="phone" name="phone" label="Phone" pattern="^(1?(-?d{3})-?)?(d{3})(-?d{4})$" messageWhenPatternMismatch="The phone number must contain 7, 10, or 11 digits. Hyphens optional." value="{!v.simpleNewContact.Phone}" required="true"/> Question: Which of these enforce field validation ?
  • 7. Demo - Let’s see...
  • 8. Lesson 2 - Validation is 2 Step! ● Depending on the component library you use: ○ For <ui:inputXXXXX /> use inputCmp.set("v.errors", [{message:"your msg"}]); See Validating Fields ○ For <lightning:input/select/textarea > use inputCmp.showHelpMessageIfInvalid();
  • 9. Helper: validateForm: function(component) { var valid = true; // Show error messages if field validation fails var uiValid = component.find('contactField').reduce( function (validFlds, inCmp) { inCmp.showHelpMessageIfInvalid(); return validFlds && inCmp.get('v.validity').valid; }, true); if (uiValid) { // Do any client side validation e.g. Account isActive } return(valid); } lightning:input In your Component Controller: handleSave: function(comp, evt, hlpr) { if (hlpr.validateForm(comp)) { //do stuff }
  • 10. ● Public examples rarely handle server errors ○ console.log() and //Do something is not enough! ● Demo: Validation Rule on Contact ● Demo: DML, Server and Dupe Warnings ● Demo: Handling the Validation Rule properly Lesson 3 - Silent but Deadly...
  • 11. ● Use console.error(); instead of console.log(); unless it’s a warning ● Display something (next lesson) ● response.getState(), has 4 states - deal with them all a. SUCCESS b. DRAFT (if using LDS and Local Cache) c. ERROR d. INCOMPLETE (offline/session expired) What does ‘properly’ mean
  • 12. Lesson 4 - How do you eat yours?
  • 13. ● throw new Error(“Arghhh!”); ● console.log() / console.error() ● <ui:outputText /> ● <ui:message ... /> ● $A.get("e.force:showToast"); ● <lightning:notificationsLibrary/> ● Spring 18: <lightning:messages/> (coming up...) Consider both desktop and mobile user experiences. Choose your weapon!
  • 14. Demo - Anyone for toast ?
  • 15. showToast vs notificationsLibrary var resultsToast = $A.get("e.force:showToast"); resultsToast.setParams({ "title": "Contact Saved", "message": "The new contact was created." }); resultsToast.fire(); <!-- Component markup --> <lightning:notificationsLibrary aura:id="notifLib"/> // JS Controller component.find('notifLib').showToast({ "variant" : “success”, "title": "Contact Saved", "message": "The new contact was created" });
  • 16. Spring 18: lightning:messages ● Spring18 (API 42.0) ○ <lightning:messages/> ○ No, it wasn’t in the release notes! See here ○ And it doesn’t appear in ./componentReference/suite.app ○ But it is in other examples in the Lightning Components Dev Guide Demo (from Spring 18: Interactive Forms article) ○ It avoids silent failures and is ‘plumbing free’ ○ Doesn’t (yet) support duplicate warnings ○ Doesn’t provide any message details (s.t. docs) ○ Keep an eye on it for the future, great catch-all for now
  • 17. ● If creating components for LightningOut/Visualforce… ○ UI Validation does work ○ showToast not supported in VF (Classic or LEX) ○ So use ui:outputtext/ui:message ● Make your error handling Environmentally Friendly! ○ What & Why: Lightning Messaging Overview ○ How: http://bobbuzzard.blogspot.co.uk/2015/11/context-is-everything.html Lesson 5 - LightningOut
  • 18. ● UI Validation ● Duplicate Rules ● Data Model Validation Rules ● Apex DMLExceptions ● Other Apex Exceptions (e.g. NullPointer, Custom) ● Salesforce Platform Errors/Limits Recap - Errors to handle
  • 19. Three areas to check within your JS error handler: ● pageErrors: e.g. Apex Exceptions, Dupe Rules, Validation ● fieldErrors: e.g. Field validation ● potentialDuplicates:* TBC! Expect multiple errors and display them all (as appropriate). Lesson 6 - Server Errors
  • 20. Three areas to check within your JS error handler: ● pageErrors: e.g. Apex Exceptions, Dupe Rules, Validation ● fieldErrors: e.g. Field validation ● potentialDuplicates:* TBC! Expect multiple errors and display them all (as appropriate). Lesson 6 - Server Errors
  • 21. // What does the user see? Account a = new Account(); insert a; // Whoops, I broke Salesforce? Lesson 7 - AuraHandledException Apex Custom Controller method using @AuraEnabled
  • 22. // What does the user see? try { Account a = new Account(); insert a; } catch (Exception ex) { AuraHandledException ahe = new AuraHandledException(“Unexpected Error: ”+ex.getMessage()); ahe.setMessage(“Err in accCreate:”+ex.getStackTrace()); throw ahe; } Lesson 7 - AuraHandledException Apex Custom Controller method using @AuraEnabled
  • 24. Lesson 7 (cont’d) Lightning Components Developer Guide: “The benefit of throwing AuraHandledException, instead of letting a system exception be returned, is that you have a chance to handle the exception more gracefully in your client code” Some quirks to be aware of: ● catch (DMLException) & throw AuraHandledException: ○ message is less readable than throwing DMLException ○ or parse out the ugly message ● catch (Exception) & throw AuraHandledException ○ Avoids “Internal Server Error” ● AuraHandledException.setMessage() for meaningful messages in debug logs instead of “Script thrown exception”
  • 25. ● Develop your own re-usable custom error component ○ Consistency across your application ○ Single point of change ○ Easy to implement ● Don’t forget i18n for your messages: ○ $A.get(“$Label.c.labelName”); ○ $A.get(“$Label.namespace.labelName”); ● Here’s a useful starting point: Lightning Error Handler plus <lightning:notificationsLibrary/> Final Lesson - Error Component
  • 26. Putting it all together...
  • 27. Summary ● Learn to debug Lightning ● Refresh/reload page or markup versions ● 2-step UI validation ● Handle all 4 callback states ● Apex AuraHandledException ● Custom reusable error/message component ○ Environment aware ○ Multi-component aware ○ Custom labels ○ Start small ● Spring 18: <lightning:messages/> during dev?