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

What's hot

Katalon studio vs selenium comparision
Katalon studio vs selenium comparisionKatalon studio vs selenium comparision
Katalon studio vs selenium comparision
Prabhusundar6
 
Integration testing - A&BP CC
Integration testing - A&BP CCIntegration testing - A&BP CC
Integration testing - A&BP CC
JWORKS powered by Ordina
 
Final Automation Testing
Final Automation TestingFinal Automation Testing
Final Automation Testing
priya_trivedi
 
A Look into Automated Web UI Test
A Look into Automated Web UI TestA Look into Automated Web UI Test
A Look into Automated Web UI Test
Dhananjay Kumar
 
Test Automation Frameworks Using Selenium | Edureka
Test Automation Frameworks Using Selenium | EdurekaTest Automation Frameworks Using Selenium | Edureka
Test Automation Frameworks Using Selenium | Edureka
Edureka!
 
selenium meetup sf talk march 2014 Selenium at Scale
selenium meetup sf talk march 2014 Selenium at Scaleselenium meetup sf talk march 2014 Selenium at Scale
selenium meetup sf talk march 2014 Selenium at Scale
David Louvton
 
Level Up Your Salesforce Unit Testing
Level Up Your Salesforce Unit TestingLevel Up Your Salesforce Unit Testing
Level Up Your Salesforce Unit Testing
Gordon Bockus
 
Java Test Automation for REST, Web and Mobile
Java Test Automation for REST, Web and MobileJava Test Automation for REST, Web and Mobile
Java Test Automation for REST, Web and Mobile
Elias Nogueira
 
Selenium Test Automation
Selenium Test AutomationSelenium Test Automation
Selenium Test Automation
BabuDevanandam
 
Lap Around Visual Studio 2010 Ultimate And TFS 2010
Lap Around Visual Studio 2010 Ultimate And TFS 2010Lap Around Visual Studio 2010 Ultimate And TFS 2010
Lap Around Visual Studio 2010 Ultimate And TFS 2010
Ed Blankenship
 
Web based automation testing on Node.js environment
Web based automation testing on Node.js environmentWeb based automation testing on Node.js environment
Web based automation testing on Node.js environment
Yu-Lin Huang
 
Execute Automation Testing in 3 Steps
Execute Automation Testing in 3 StepsExecute Automation Testing in 3 Steps
Execute Automation Testing in 3 Steps
ExecuteAutomation
 
Colorful world-of-visual-automation-testing-latest
Colorful world-of-visual-automation-testing-latestColorful world-of-visual-automation-testing-latest
Colorful world-of-visual-automation-testing-latest
Onur Baskirt
 
Agile test-management-test-rail-lastest
Agile test-management-test-rail-lastestAgile test-management-test-rail-lastest
Agile test-management-test-rail-lastest
Onur Baskirt
 
Automation With A Tool Demo
Automation With A Tool DemoAutomation With A Tool Demo
Automation With A Tool Demo
Nivetha Padmanaban
 
Automated Testing using JavaScript
Automated Testing using JavaScriptAutomated Testing using JavaScript
Automated Testing using JavaScript
Simon Guest
 
ProtractorJS for automated testing of Angular 1.x/2.x applications
ProtractorJS for automated testing of Angular 1.x/2.x applicationsProtractorJS for automated testing of Angular 1.x/2.x applications
ProtractorJS for automated testing of Angular 1.x/2.x applications
Binary Studio
 
Test Automation Framework Designs
Test Automation Framework DesignsTest Automation Framework Designs
Test Automation Framework Designs
Sauce Labs
 
Automation using Javascript
Automation using JavascriptAutomation using Javascript
Automation using Javascript
khanhdang1214
 
Setup and run automated test framework for android application
Setup and run automated test framework for android applicationSetup and run automated test framework for android application
Setup and run automated test framework for android application
Konstantin Natalukha
 

What's hot (20)

Katalon studio vs selenium comparision
Katalon studio vs selenium comparisionKatalon studio vs selenium comparision
Katalon studio vs selenium comparision
 
Integration testing - A&BP CC
Integration testing - A&BP CCIntegration testing - A&BP CC
Integration testing - A&BP CC
 
Final Automation Testing
Final Automation TestingFinal Automation Testing
Final Automation Testing
 
A Look into Automated Web UI Test
A Look into Automated Web UI TestA Look into Automated Web UI Test
A Look into Automated Web UI Test
 
Test Automation Frameworks Using Selenium | Edureka
Test Automation Frameworks Using Selenium | EdurekaTest Automation Frameworks Using Selenium | Edureka
Test Automation Frameworks Using Selenium | Edureka
 
selenium meetup sf talk march 2014 Selenium at Scale
selenium meetup sf talk march 2014 Selenium at Scaleselenium meetup sf talk march 2014 Selenium at Scale
selenium meetup sf talk march 2014 Selenium at Scale
 
Level Up Your Salesforce Unit Testing
Level Up Your Salesforce Unit TestingLevel Up Your Salesforce Unit Testing
Level Up Your Salesforce Unit Testing
 
Java Test Automation for REST, Web and Mobile
Java Test Automation for REST, Web and MobileJava Test Automation for REST, Web and Mobile
Java Test Automation for REST, Web and Mobile
 
Selenium Test Automation
Selenium Test AutomationSelenium Test Automation
Selenium Test Automation
 
Lap Around Visual Studio 2010 Ultimate And TFS 2010
Lap Around Visual Studio 2010 Ultimate And TFS 2010Lap Around Visual Studio 2010 Ultimate And TFS 2010
Lap Around Visual Studio 2010 Ultimate And TFS 2010
 
Web based automation testing on Node.js environment
Web based automation testing on Node.js environmentWeb based automation testing on Node.js environment
Web based automation testing on Node.js environment
 
Execute Automation Testing in 3 Steps
Execute Automation Testing in 3 StepsExecute Automation Testing in 3 Steps
Execute Automation Testing in 3 Steps
 
Colorful world-of-visual-automation-testing-latest
Colorful world-of-visual-automation-testing-latestColorful world-of-visual-automation-testing-latest
Colorful world-of-visual-automation-testing-latest
 
Agile test-management-test-rail-lastest
Agile test-management-test-rail-lastestAgile test-management-test-rail-lastest
Agile test-management-test-rail-lastest
 
Automation With A Tool Demo
Automation With A Tool DemoAutomation With A Tool Demo
Automation With A Tool Demo
 
Automated Testing using JavaScript
Automated Testing using JavaScriptAutomated Testing using JavaScript
Automated Testing using JavaScript
 
ProtractorJS for automated testing of Angular 1.x/2.x applications
ProtractorJS for automated testing of Angular 1.x/2.x applicationsProtractorJS for automated testing of Angular 1.x/2.x applications
ProtractorJS for automated testing of Angular 1.x/2.x applications
 
Test Automation Framework Designs
Test Automation Framework DesignsTest Automation Framework Designs
Test Automation Framework Designs
 
Automation using Javascript
Automation using JavascriptAutomation using Javascript
Automation using Javascript
 
Setup and run automated test framework for android application
Setup and run automated test framework for android applicationSetup and run automated test framework for android application
Setup and run automated test framework for android application
 

Similar to London SF Developers: Custom Lightning Component Error Handling

Lightning page optimization &amp; best practices
Lightning page optimization &amp; best practicesLightning page optimization &amp; best practices
Lightning page optimization &amp; best practices
Gaurav Jain
 
ASP.NET 05 - Exception Handling And Validation Controls
ASP.NET 05 - Exception Handling And Validation ControlsASP.NET 05 - Exception Handling And Validation Controls
ASP.NET 05 - Exception Handling And Validation Controls
Randy Connolly
 
Lightning Talk: JavaScript Error Handling
Lightning Talk: JavaScript Error HandlingLightning Talk: JavaScript Error Handling
Lightning Talk: JavaScript Error Handling
Nick Burwell
 
Apex Enterprise Patterns: Building Strong Foundations
Apex Enterprise Patterns: Building Strong FoundationsApex Enterprise Patterns: Building Strong Foundations
Apex Enterprise Patterns: Building Strong Foundations
Salesforce Developers
 
Error management
Error managementError management
Error management
daniil3
 
JAX 08 - Agile RCP
JAX 08 - Agile RCPJAX 08 - Agile RCP
JAX 08 - Agile RCP
Heiko Seeberger
 
Frontend training
Frontend trainingFrontend training
Frontend training
Adrian Caetano
 
J Unit
J UnitJ Unit
Php exceptions
Php exceptionsPhp exceptions
Php exceptions
Damian Sromek
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
Naresh Jain
 
AngularJs Style Guide
AngularJs Style GuideAngularJs Style Guide
AngularJs Style Guide
Chiew Carol
 
$Cash
$Cash$Cash
$Cash
$Cash$Cash
Stopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestStopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under Test
Seb Rose
 
DotNet unit testing training
DotNet unit testing trainingDotNet unit testing training
DotNet unit testing training
Tom Tang
 
WebTest - Efficient Functional Web Testing with HtmlUnit and Beyond
WebTest - Efficient Functional Web Testing with HtmlUnit and BeyondWebTest - Efficient Functional Web Testing with HtmlUnit and Beyond
WebTest - Efficient Functional Web Testing with HtmlUnit and Beyond
mguillem
 
Ppt lesson 06
Ppt lesson 06Ppt lesson 06
Ppt lesson 06
Linda Bodrie
 
Ppt lesson 06
Ppt lesson 06Ppt lesson 06
Ppt lesson 06
Linda Bodrie
 
Ppt lesson 06
Ppt lesson 06Ppt lesson 06
Ppt lesson 06
Linda Bodrie
 
Lecture 20-21
Lecture 20-21Lecture 20-21
Lecture 20-21
talha ijaz
 

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

Lightning page optimization &amp; best practices
Lightning page optimization &amp; best practicesLightning page optimization &amp; best practices
Lightning page optimization &amp; best practices
 
ASP.NET 05 - Exception Handling And Validation Controls
ASP.NET 05 - Exception Handling And Validation ControlsASP.NET 05 - Exception Handling And Validation Controls
ASP.NET 05 - Exception Handling And Validation Controls
 
Lightning Talk: JavaScript Error Handling
Lightning Talk: JavaScript Error HandlingLightning Talk: JavaScript Error Handling
Lightning Talk: JavaScript Error Handling
 
Apex Enterprise Patterns: Building Strong Foundations
Apex Enterprise Patterns: Building Strong FoundationsApex Enterprise Patterns: Building Strong Foundations
Apex Enterprise Patterns: Building Strong Foundations
 
Error management
Error managementError management
Error management
 
JAX 08 - Agile RCP
JAX 08 - Agile RCPJAX 08 - Agile RCP
JAX 08 - Agile RCP
 
Frontend training
Frontend trainingFrontend training
Frontend training
 
J Unit
J UnitJ Unit
J Unit
 
Php exceptions
Php exceptionsPhp exceptions
Php exceptions
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
AngularJs Style Guide
AngularJs Style GuideAngularJs Style Guide
AngularJs Style Guide
 
$Cash
$Cash$Cash
$Cash
 
$Cash
$Cash$Cash
$Cash
 
Stopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestStopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under Test
 
DotNet unit testing training
DotNet unit testing trainingDotNet unit testing training
DotNet unit testing training
 
WebTest - Efficient Functional Web Testing with HtmlUnit and Beyond
WebTest - Efficient Functional Web Testing with HtmlUnit and BeyondWebTest - Efficient Functional Web Testing with HtmlUnit and Beyond
WebTest - Efficient Functional Web Testing with HtmlUnit and Beyond
 
Ppt lesson 06
Ppt lesson 06Ppt lesson 06
Ppt lesson 06
 
Ppt lesson 06
Ppt lesson 06Ppt lesson 06
Ppt lesson 06
 
Ppt lesson 06
Ppt lesson 06Ppt lesson 06
Ppt lesson 06
 
Lecture 20-21
Lecture 20-21Lecture 20-21
Lecture 20-21
 

Recently uploaded

Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise EditionWhy Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Envertis Software Solutions
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
Green Software Development
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
Rakesh Kumar R
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
Green Software Development
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
Hornet Dynamics
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 
What is Master Data Management by PiLog Group
What is Master Data Management by PiLog GroupWhat is Master Data Management by PiLog Group
What is Master Data Management by PiLog Group
aymanquadri279
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
Philip Schwarz
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
Green Software Development
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
kalichargn70th171
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
SOCRadar
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptxLORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
lorraineandreiamcidl
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
Remote DBA Services
 
SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
Hironori Washizaki
 
What is Augmented Reality Image Tracking
What is Augmented Reality Image TrackingWhat is Augmented Reality Image Tracking
What is Augmented Reality Image Tracking
pavan998932
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
TheSMSPoint
 

Recently uploaded (20)

Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise EditionWhy Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 
What is Master Data Management by PiLog Group
What is Master Data Management by PiLog GroupWhat is Master Data Management by PiLog Group
What is Master Data Management by PiLog Group
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptxLORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
 
SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
 
What is Augmented Reality Image Tracking
What is Augmented Reality Image TrackingWhat is Augmented Reality Image Tracking
What is Augmented Reality Image Tracking
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
 

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?