エラーの発生および処理
このフレームワークでは、復旧できないアプリケーションエラーおよび復旧できるアプリケーションエラーを JavaScript コードで柔軟に対処できます。たとえば、サーバ側の応答のエラーを処理するときに、これらのエラーをコールバック内に発生させることができます。
復旧できないエラー
アプリケーションが正常に起動できないエラーなどの復旧できないエラーには、throw new Error("error message here") を使用します。これでエラーメッセージが表示されます。
次の例では、JavaScript コントローラでの基本的な復旧できないエラーの発生を示します。
1<!--c:unrecoverableError-->
2<aura:component>
3 <lightning:button label="throw error" onclick="{!c.throwError}"/>
4</aura:component>クライアント側コントローラのソースを次に示します。
1/*unrecoverableErrorController.js*/
2({
3 throwError : function(component, event){
4 throw new Error("I can’t go on. This is the end.");
5 }
6})復旧できるエラー
復旧できるエラーを処理するには、ui:message などのコンポーネントを使用して、その問題につい���ユーザに通知します。
次のサンプルでは、JavaScript コントローラでの基本的な復旧できるエラーの発生およびキャッチを示します。
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>クライアント側コントローラのソースを次に示します。
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 ["ui:outputText",{
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})この例では、コントローラコードが常にエラーを発生させてキャッチします。エラーのメッセージは、動的に作成される ui:message コンポーネントでユーザに表示されます。ui:message のボディは、エラーテキストを含む ui:outputText コンポーネントです。