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

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 - 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

Oracle APEX 20.1 Friendly URLs

Friendly URLs! It's been one of the most wanted feature in APEX from very initial days. It's one of the main complaints we hear from customers, especially for websites which are open for public. There are several benefits of having a friendly URL besides better user experience. Finally, the wait is over! APEX team has implemented this feature, probably in the most simplest way possible (for APEX developers). Big Kudos to the APEX Team. All you need to do is, just turn on a flag in application properties. Yes, you read it right.. Now, after enabling this flag, all APEX URLs will switch to new friendly URLs New URL Format: Example link - https://apex.oracle.com/pls/apex/hari/r/demo_app/home?session=714815362925554 Part-1:  https://apex.oracle.com/pls/apex/ - Host details, there is no change here Part-2: /hari/r -  Here hari  is work-space path prefix and  r  stands for router. You can modify "Path Prefix" at "Workspace Administration

Interactive Grid - Aggregate Validations

In Oracle APEX, validating Interactive Grid (IG) data at row level, is easy and straight forward. You just need to select "Editable Region" for the validation and then you can use IG column values using :COLUMN_NAME syntax in SQL and PL/SQL code. However, if you want to create a validation at table level or validation which uses multiple rows data, then it becomes tricky. Let's consider a simple example of budget planning, where you can allocate percentage for each category, like 10% for healthcare, 10% for education etc. Here, we need to implement a simple table level validation to ensure total allocation % does not exceed 100. Please refer  Interactive Grid - Client Side Aggregate Validations  for implementing this validation entirely on client side. You can use technique explained below for more complex validations that can't be done on client side (checking data from multiple tables, number of rows in IG are more than 50) Before jumping into the implemen