Newer Version Available

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

Error Handling with the AJAX Toolkit

The AJAX Toolkit provides the ability to handle errors for synchronous and asynchronous calls.

Error Handling for Synchronous Calls

If the API call fails, then the AJAX Toolkit throws an exception. The exception contains all the available error information. For example:

1<html>
2<head>
3    <script src="/soap/ajax/54.0/connection.js" type="text/javascript"></script>
4 
5    <script>
6 
7        function setupPage() {
8            var output = document.getElementById("output");
9            var startTime = new Date().getTime()
10
11             try {
12                var queryResult = sforce.connection.query("Select Id, Name, Industry From  
13                     Account order by Industry limit 30");
14                layoutResults(queryResult, output, startTime);
15            } catch(error) {
16                queryFailed(error, output);
17            }
18        }
19 
20        function queryFailed(error, out) {
21            out.innerHTML = "<font color=red>An error has occurred:</font> <p>" + error;
22        }
23 
24        function layoutResults(queryResult, out, startTime) {
25            var timeTaken = new Date().getTime() - startTime;
26 
27            if (queryResult.size > 0) {
28                var output = "";
29                var records = queryResult.getArray('records');
30 
31                for (var i = 0; i < records.length; i++) {
32                    var account = records[i];
33                    output += account.Id + " " + account.Name + " [Industry - "  
34                         + account.Industry + "]<BR>";
35                }
36 
37                out.innerHTML = output + "<BR> query complexted in: " + timeTaken + " ms.";
38            } else {
39                out.innerHTML = "No records matched.";
40            }
41        }
42 
43    </script>
44</head>
45
46 <body onload="setupPage()">
47<div id="output"></div>
48</body>
49</html>

Error Handling for Asynchronous Calls

For asynchronous calls, the onFailure property of the asynchronous object is called. For example:

1connection.query("Select Name From Account", 
2   {onSuccess: displayResult,
3       onFailure: queryFailed});
4
5function displayResult(result){}
6function queryFailed(error){}

If the onFailure property was not defined, the AJAX Toolkit pops up a new read-only browser window showing the error.