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.
<!--c:unrecoverableError--> <aura:component> <lightning:button label="throw error" onclick="{!c.throwError}"/> </aura:component>
Here is the client-side controller source.
/*unrecoverableErrorController.js*/ ({ throwError : function(component, event){ throw new Error("I can’t go on. This is the end."); } })
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.
<!--c:recoverableError--> <aura:component> <p>Click the button to trigger the controller to throw an error.</p> <div aura:id="div1"></div> <lightning:button label="Throw an Error" onclick="{!c.throwErrorForKicks}"/> </aura:component>
Here is the client-side controller source.
/*recoverableErrorController.js*/ ({ throwErrorForKicks: function(cmp) { // this sample always throws an error to demo try/catch var hasPerm = false; try { if (!hasPerm) { throw new Error("You don't have permission to edit this record."); } } catch (e) { $A.createComponents([ ["ui:message",{ "title" : "Sample Thrown Error", "severity" : "error", }], ["ui:outputText",{ "value" : e.message }] ], function(components, status, errorMessage){ if (status === "SUCCESS") { var message = components[0]; var outputText = components[1]; // set the body of the ui:message to be the ui:outputText message.set("v.body", outputText); var div1 = cmp.find("div1"); // Replace div body with the dynamic component div1.set("v.body", message); } else if (status === "INCOMPLETE") { console.log("No response from server or client is offline.") // Show offline error } else if (status === "ERROR") { console.log("Error: " + errorMessage); // Show error message } } ); } } })
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.