Newer Version Available
Throwing and Handling Errors
Unrecoverable Errors
Use throw new Error("error message here") for unrecoverable errors, such as an error that prevents your app from starting successfully. The error message is displayed.
This example shows you the basics of throwing an unrecoverable error in a JavaScript controller.
1<!--c:unrecoverableError-->
2<aura:component>
3 <lightning:button label="throw error" onclick="{!c.throwError}"/>
4</aura:component>Here is the client-side controller source.
1/*unrecoverableErrorController.js*/
2({
3 throwError : function(component, event){
4 throw new Error("I can’t go on. This is the end.");
5 }
6})Recoverable Errors
To handle recoverable errors, use a component, such as ui:message, to tell users about the problem.
This sample shows you the basics of throwing and catching a recoverable error in a JavaScript controller.
1<!--c:recoverableError-->
2<aura:component>
3 <p>Click the button to trigger the controller to throw an error.</p>
4 <div aura:id="div1"></div>
5
6 <lightning:button label="Throw an Error" onclick="{!c.throwErrorForKicks}"/>
7</aura:component>Here is the client-side controller source.
1/*recoverableErrorController.js*/
2({
3 throwErrorForKicks: function(cmp) {
4 // this sample always throws an error to demo try/catch
5 var hasPerm = false;
6 try {
7 if (!hasPerm) {
8 throw new Error("You don't have permission to edit this record.");
9 }
10 }
11 catch (e) {
12 $A.createComponents([
13 ["ui:message",{
14 "title" : "Sample Thrown Error",
15 "severity" : "error",
16 }],
17 ["lightning:formattedText",{
18 "value" : e.message
19 }]
20 ],
21 function(components, status, errorMessage){
22 if (status === "SUCCESS") {
23 var message = components[0];
24 var outputText = components[1];
25 // set the body of the ui:message to be the ui:outputText
26 message.set("v.body", outputText);
27 var div1 = cmp.find("div1");
28 // Replace div body with the dynamic component
29 div1.set("v.body", message);
30 }
31 else if (status === "INCOMPLETE") {
32 console.log("No response from server or client is offline.")
33 // Show offline error
34 }
35 else if (status === "ERROR") {
36 console.log("Error: " + errorMessage);
37 // Show error message
38 }
39 }
40 );
41 }
42 }
43})The controller code always throws an error and catches it in this example. The message in the error is displayed to the user in a dynamically created ui:message component. The body of the ui:message is a ui:outputText component containing the error text.