Skip to main content

Handling JavaScript Errors - Part 1

Before APEX version 5.0, there were only handful of documented JavaScript (JS) functions in APEX. Now, there are several JavaScript namespaces and hundreds of functions and methods available in Oracle APEX. From APEX 18.1, separate documentation section "JavaScript API Reference" is also added for JavaScript. So, it's evident that usage of JavaScript in APEX is increasing every day and with every release. 

But, how are you handling JavaScript errors in your APEX applications? For server-side errors, we can use EXCEPTION block and we can also define "Error Handling Function" at application level. What about JavaScript code? Can we do something similar for JavaScript errors?

In this blog, I am going to briefly explain about JavaScript errors and how we can handle them in general and how we can handle them at application level.

Handling JavaScript Errors in Oracle APEX

Introduction

Browsers have JavaScript engine inside them. Mozilla's TraceMonkey, Google's v8 are examples for JavaScript engines. JavaScript engines perform both code interpretation and execution. Browsers execute HTML code from top to bottom. When browser finds a script tag, then control is shifted to JS engine. Then JS Engine interprets (and/or executes) the code from top to bottom. When JS Engine finds any error during interpretation, then JS engine will throw the error and it will stop interpreting any further code. Errors occurred during interpretation are called "Syntax Errors" and errors occurred during code execution are called "Runtime Errors".

Syntax Errors

For e.g. below JavaScript is invalid and it will throw Uncaught SyntaxError: missing ) after argument list error after the page load.

function doTask1(pValue)
{
    console.log(pValue;
}

When a Syntax Errors occurs, then entire JS block code is invalidated. When there is a syntax error, then all the variables, functions defined in the JS block will be invalidated. For e.g. consider below JS Code which has two blocks.

<!--JS Block-1-->
<script type="text/javascript">
    // function with-out any issues
    function noIssuesBlock1() {
        console.log('I am noIssuesBlock1');
    }
    // below function throws syntax error 
    function doTask1(pValue) {
        console.log(pValue;
    }
</script>
<!--JS Block-2-->
<script type="text/javascript">
    // function with-out any issues
    function noIssuesBlock2() {
        console.log('I am noIssuesBlock2');
    }
</script>

Create a new APEX page and put above code in "HTML Header" section. Save and run the page. We will see below error in browser console.

Uncaught SyntaxError: missing ) after argument list

Now, try to invoke noIssuesBlock1() using browser console, then we will get Uncaught ReferenceError: noIssuesBlock1 is not defined error. Try to invoke noIssuesBlock2(), it will work without any errors. So it is clear that entire block-1 code is invalidated when a syntax error is encountered. 

In general, it's very unlikely that you have syntax errors in production applications. Also, we can't catch syntax errors using traditional error handling approaches in JavaScript. So, I am not going discuss about Syntax Errors further.

Runtime Errors

Run time errors are errors that are raised during execution of the code. For e.g. consider below code. 

function doTask1()
{
    console.log(pValue);
}

As per JS syntax it all looks good. So we don't get any error during initial page load. But when we invoke it, then we will get Uncaught ReferenceError: pValue is not defined error.

When JS Engine gets a runtime error, then error will be thrown and code execution will be stopped. For e.g. Create a new empty page in APEX and put below JS code in "Function and Global Variable Declaration" section.

// function with-out any issues
function noIssues() {
    console.log('I am noIssues');
}
// below function throws runtime error
function doTask1() {
    console.log(pValue);
}
// function with-out any issues
function anotherNoIssues() {
    console.log('I am anotherNoIssues');
}

Now, put below code in "JavaScript > Execute when Page Loads" section.

// noIssues will be executed
noIssues();
// doTask1 will throw runtime error
doTask1();
// anotherNoIssues will not be called
anotherNoIssues();

When we save and run the page, we can see below output in error in browser console.

JavaScript Runtime Error

As we can see noIssues() is executed successfully, doTask1() is executed but ended up with an error and anotherNoIssues() is not been called. Same thing will happen with Dynamic Actions (DA). 

Let's create 3 DAs that are executed during "Page Load" event as below.

DA-1:
  • Name: DA-1
  • Execution Options:
    • Sequence: 10
  • When:
    • Event: Page Load
  • True Action:
    • Action: Execute JavaScript Code
    • Settings:
      • Code: noIssues();
DA-2:
  • Name: DA-2
  • Execution Options:
    • Sequence: 20
  • When:
    • Event: Page Load
  • True Action:
    • Action: Execute JavaScript Code
    • Settings:
      • Code: doTask1();
DA-3:
  • Name: DA-3
  • Execution Options:
    • Sequence: 30
  • When:
    • Event: Page Load
  • True Action:
    • Action: Execute JavaScript Code
    • Settings:
      • Code: anotherNoIssues();
In such case, DA-1 will get executed successfully. DA-2 will get executed and it will throw JS error and DA-3 won't be executed. When there are multiple DAs defined with "Page Load" event, then DAs are executed based on the "Sequence" specified at DA level.

Handling Runtime Errors

Let's create an empty page (Page 1) and put below JavaScript code in "Function and Global Variable Declaration" section.

function performChecks() {
    console.log('performChecks executed successfully.');
}

function doTask1() {
    console.log(pValue);
}

Let's put below code in "Execute when Page Loads" section.

performChecks();
doTask1();

Save and run the page. If you see the browser console, then we can see below output.


We can handle these runtime errors using try-catch-finally statement.

try {
    // try to execute code specified in this block
}
catch (e) {
    // code to handle any runtime errors from the try block
}
finally {
    // clean up code that is always executed, irrespective of any runtime errors
}

We can use try-catch-finally either inside the function doTask1 or while calling this function. Let's change our "Execute when Page Loads" section code as below in Page 1.

performChecks();
try {
    doTask1();
}
catch (e) {
    console.log('Error occurred while executing doTask1: ' + e.message);
}
finally {
    console.log('Code from finally block');
}

Here, we have handled the errors inside our page code. But, what if, we have JS code in several places and in several pages? Is there any better way to handle these errors globally? 

Yes, there is! To handle JavaScript errors globally, let's define an DA in Page 0 as below.
  • Name: Handle Errors or any proper name
  • Execution Options:
    • Sequence: 0
  • When:
    • Event: Page Load
  • True Action:
    • Action: Execute JavaScript Code
    • Code: As shown below
window.addEventListener('error', function (event) {
    // write code here to handle JS errors
    // data what we can get from error event
    console.log(event);
    console.log(event.type);
    console.log(event.message);
    console.log(window.location.href);
    console.log(event.lineno);
    if (apex.debug.getLevel() == 0) {
        // debug off
        // do not show errors in Browser console    
        event.preventDefault();
    }
});

JavaScript error event gives lot of information about the error. Few important error details are logged to console in the above code example.

If you trying this code in normal pages (not in Page 0), then don't put window.addEventListener code in "Execute when Page Loads" section. Because, APEX first executes DAs with event "Page Load" first and then, the code specified in "Execute when Page Loads" is executed. So, if we use "Execute when Page Loads" section, then any errors that we may get in page load DAs will not be handled.

Now, let's rollback "Execute when Page Loads" section code in Page 1 as below.

performChecks();
doTask1();

Save the changes and run the page. Now, we can see error from Page 1 is captured using DA defined in Page 0 and we can see messages logged from Page 0 DA in browser console.

That's it for now. In my next blogpost, I will provide some ideas on how we can log these errors to the database.

Thank You 🙏

💐 Wish you happy new year 2021 💐


Comments

Sasha Gomanuke said…
Hari, appreciate for YOur experience sharing!
Would You comment alternative approach of error catching, when we declare on 0 Page
window.onerror = function(pMessage){ showErrors(pMessage); }

Where showErrors is our code with console.log etc.

Thank You.
Hari said…
Hi,

If you have requirement to support legacy browsers, then you can use window.onerror approach. Below discussion on stackoverflow has some good points.

window.onerror vs window.addEventListener('error', callback)

Popular posts from this blog

Interactive Grid - Conditional Enable/Disable

In this blogpost, I am going to discuss few approaches using which we can conditionally enable/disable Interactive Grid (IG) column(s) based on other column(s) values. Note:    There is a bug  30801170  in APEX 19.2/20.1 with respect to "enable/disable" dynamic actions for IG columns. Workaround for this bug is provided at the end of this blogpost . This bug has been fixed in APEX version 20.2. Client Side Only Conditions If conditions to enable/disable are simple, then we can check those conditions easily on the client side. For e.g. let's consider IG on EMP table with following SQL Query. SELECT EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO FROM EMP Let's consider the requirement as - Enable "Commission" column only when JOB is equals to 'SALESMAN' and disable "Commission" column in all other cases. This can be done declaratively using dynamic actions (DA) DA "Enable/Disable Commission - 1" Create DA and give it a prope

Interactive Grid - Bulk Operation on Selected Rows

What's the Problem? Let's say you have an IG on employee table and you want to update selected employees commission based on user's input. Ideally, it should be very simple, where you can write UPDATE statement in page process and select IG region as "Editable Region" under "Execution Options" of the page process. But, when you select rows and submit page, you can see that, this process won't get executed! The reason is  Selection of 'Row Selector' check-boxes is not considered as row-change. Thus selected rows are not submitted to server. So, is there any work around?  Yes! Luckily there are lot of JavaScript (JS) APIs available to work with IG. If you are not already aware, you can refer "APEX IG Cookbook"  or  JavaScript API Reference documentation. If we continue with above Employee IG example, when user selects IG rows, enters "Commission %" and clicks on "Update Commission" button, then we can writ

Few tips on Gantt Charts

Oracle APEX offers several beautiful chart types which are based on Oracle JET Data Visualizations. Gantt Chart is one such beautiful and useful chart. However, when I have searched in Google for some help on Gantt Charts, there are not many blogs posts talking about it. So, I thought, I could write one with few basic tips which I have learned this year. I have used Gantt Chart to display employees calendar data and my targeted output was something like below. Pic-1 Looks simple, correct? However, it's little tricky to get there. Multiple Tasks Per Row: When I look at the output, first I thought, I will have to write a query which gives tasks data and employee data with 1 row per task. That is, if there are 10 tasks to be displayed, then there should be 10 rows in SQL query output. But, it's not correct. Instead, I should have 1 row for each task + 1 row for each employee (parent). So I need to write a query which will output data in below format. Pic-2 A