SlideShare ist ein Scribd-Unternehmen logo
1 von 28
Downloaden Sie, um offline zu lesen
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?

Weitere ähnliche Inhalte

Was ist angesagt?

Final Automation Testing
Final Automation TestingFinal Automation Testing
Final Automation Testing
priya_trivedi
 

Was ist angesagt? (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
 

Ähnlich wie London SF Developers: Custom Lightning Component Error Handling

Error management
Error managementError management
Error management
daniil3
 
AngularJs Style Guide
AngularJs Style GuideAngularJs Style Guide
AngularJs Style Guide
Chiew Carol
 

Ähnlich wie 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
 

Kürzlich hochgeladen

Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 

Kürzlich hochgeladen (20)

Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 

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?