Newer Version Available

This content describes an older version of this product. View Latest

Throwing Errors

The framework gives you flexibility in handling unrecoverable and recoverable app errors in JavaScript code.

Unrecoverable Errors

Use $A.error("error message here") for unrecoverable errors, such as an error that prevents your app from starting successfully. It shows a stack trace on the page.

Recoverable Errors

To handle recoverable errors, use a component, such as ui:message or ui:dialog, to tell the user about the problem.

This sample shows you the basics of throwing and catching an error in a JavaScript controller.

Component source

1swfobject.registerObject("clippy.codeblock-0", "9");<aura:component>
2    <p>Click the button to trigger the controller to throw an error.</p>
3    <div aura:id="div1"></div>
4
5    <ui:button label="Throw an Error" press="{!c.throwErrorForKicks}"/>
6</aura:component>
7

Client-side controller source

1swfobject.registerObject("clippy.codeblock-1", "9");({
2    throwErrorForKicks: function(cmp) {
3        // this sample always throws an error
4        var hasPerm = false;
5        try {
6            if (!hasPerm) {
7                throw new Error("You don't have permission to edit this record.");
8            }
9        }
10        catch (e) {
11            // config for a dynamic ui:message component
12            var componentConfig = {
13                componentDef : "markup://ui:message",
14                attributes : {
15                    values : {
16                        title : "Sample Thrown Error",
17                        severity : "error",
18                        body : [
19                            {
20                                componentDef : "markup://ui:outputText",
21                                attributes : {
22                                    values : {
23                                        value : e.message
24                                    }
25                                }
26                            }
27                        ]
28                    }
29                }
30            };
31
32            $A.componentService.newComponentAsync(
33                this,
34                function(message) {
35                    var div1 = cmp.find("div1");
36                    
37                    // Replace existing body with the dynamic component
38                    div1.set("v.body", message);
39                },
40                componentConfig
41            );
42            
43            
44
45        }
46    }
47})
48

See the controller code for an example of throwing an error in a try-catch block. The message in the error is displayed to the user in a dynamically created ui:message component.