handle an exception within the initializer of its object

I'm currently working with an Ajax object that is utilized in various other objects to load 'Json' files.

One issue I'm facing is trying to catch the 404 'Not found' exception thrown in the initializer object. However, every attempt results in:

Uncaught Exception : *********

Here is a snippet of the code in question:

_ajax_params.xmlhttp.onreadystatechange = function() {
    if (_ajax_params.xmlhttp.readyState==4 && _ajax_params.xmlhttp.status==200) {
        _ajax_params.response = _ajax_params.xmlhttp.responseText;
        if (typeof afterClosure == 'function') {
            afterClosure(_ajax_params.response);
        }
        COMMON.always(_ajax_params.response);
    } else if (_ajax_params.xmlhttp.status == 404) {
        throw 'File not found';
    }
};

Within the initializer object:

try {
   Base.include.json(url, 1);
} catch (e) {
   console.error(e);
   Base.include.json(url,2);
}

Despite attempting to re-throw the exception, I keep encountering the same issue.

Answer №1

The callback you've defined may be encapsulated within a try-catch block, but keep in mind that it gets executed outside of this block when the event is triggered. Consequently, any exceptions thrown within the callback won't be caught by the surrounding block.

If you're interested in seeing how this works in practice, check out this demonstration.

Instead of using throw 'File not found';, consider invoking Base.include.json(url,2).

Additionally, it's advisable to only check the status if you're certain that the readyState is at 4; however, this is more of a minor detail.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error message thrown: "The reference to $ is undefined. Are you using Jsfiddle?"

As a newcomer to javascript, I decided to experiment with creating a navigation bar that only appears when the user scrolls down using JSFiddle. However, when I transferred the code to Dreamweaver, it stopped functioning. Why is this happening? I've ...

Using React to create multiple modals and dynamically passing props

Each item in my list (ProjectActivityList) has an Edit button which, when clicked, should open a modal for editing that specific item. The modal requires an ID to identify the item being edited. var ProjectActivities = React.createClass({ onEditItem: ...

Testing with karma/jasmine in AngularJS can lead to issues when there are conflicts between test

Currently experiencing challenges while running my midway tests (or integration tests, which are halfway between unit tests and E2E tests). Working with an AngularJS build featuring RequireJS, I am utilizing the RequireJS plugin in Karma to run the tests. ...

What is the best way to incorporate a changing variable within an htmx request?

One of the endpoints in my site requires an ID to be passed as a parameter. For example: mysite.com/product/{id}?limit=5 I'm wondering how to pass the 'id' variable in the hx-get attribute. I can utilize AlpineJS or vanilla JS for this tas ...

How to use jQuery with multiple selectors?

I am attempting to create a feature where multiple links are highlighted when one is clicked. However, I am encountering an issue where only the link that is clicked is being highlighted, rather than all three links. Below is the code snippet: $('#v ...

What steps are necessary to add a Contact Us form to my HTML website?

Currently, I am searching for a way to add a "Contact Us" section to my website that is completely HTML-based. I believe the best approach would involve using a PHP script to handle sending emails from a form on the Contact Us page, but I am not familiar ...

Issues encountered with AngularJs filter search functionality

Why am I having trouble adapting this search filter from here? This is what my code looks like: controllers.js angular.module('starter.controllers', ['starter.services']) .controller('AppCtrl', function($scope, $ionicModal ...

What could possibly be causing a syntax error in my JavaScript code?

<script type="text/javascript> $(document).ready(function(){ $("a.grouped_elements").fancybox( 'transitionIn' : 'elastic', 'transitionOut' : 'elastic', 'speedIn' : 600, ...

Is there a way to ensure that the elements created by the select form are only generated once?

I have a JavaScript function that dynamically creates paragraph and input elements based on user selection in HTML. However, I am looking to optimize the code so that each element is only created once. Snippet of JavaScript code: function comFunction(sel ...

Avoiding a jest compile error and executing the test efficiently

Here is my Vue.js code snippet: export default { name: 'App', components: { }, created() { let t = typeof t === 'undefined' ? {} : t; // ISSUE LINE } } The ISSUE LINE runs successfully in the browser without any errors an ...

Extracting Raw Body from Stripe Webhook in NextJS

I'm feeling frustrated trying to get a raw body passed for the Stripe webhook in NextJS! Despite trying numerous solutions from various sources, I just can't seem to get it to work. Calling upon the developers with special powers (of which I am ...

Verify that JavaScript is capable of performing mathematical operations such as addition and multiplication successfully

When dealing with a specific set of "Strings" that represent integers in an addition operation, how can one determine if the calculation is feasible in javascript? For example: 2 + 2 (certainly possible) 20000000000000000 - 1 (impossible) 2e50 + 2e60 (i ...

Strange CSS/browser storage glitch

UPDATE: JUST REALIZED THIS ISSUE IS ONLY OCCURRING ON FIREFOX, NOT CHROME ANOTHER UPDATE: Oddly enough, this problem only occurs locally. When I push it to GitHub, everything works fine. So strange. I suppose that means it's not a major issue. On my ...

Passing data from an API in Vue.js to a different page

I'm a beginner with Vue Js and I'm looking for guidance on how to send data between two components. Currently, I am working on a Vue app that fetches a list of users from an API and displays them. My goal is to transfer data between these compone ...

Can you explain the process of obtaining getServerSideProps results for my IndexPage?

Having trouble with the getServerSideProps function. I'm a beginner and struggling to figure out why it's not running properly. Spent hours trying to fix it, but still getting undefined in the IndexPage console.log(props.data) export default fun ...

The situation where a Javascript switch case continues to fall through to the default case even when a 'break' statement

I am currently setting up a node.js discord bot that utilizes firebase to save a user's status. My switch statement is functioning smoothly, handling each command effectively. The default case looks like this: default: message.reply("Unknown comm ...

My code fails to recognize the top property when the window size is 1300px

Error at the Top Not Being Recognized: Hello, I am facing an issue where the top part of the webpage does not behave correctly when the window size is less than 1300px. The condition set for 100% top only applies after refreshing the page; otherwise, it d ...

Deleting an element from HTML using jQuery

In the midst of creating a system that allows users to construct their own navigation structure, I have encountered a stumbling block. The idea is that when a user lands on the site, they are presented with a list of available topics from which they can ch ...

Struggling to modify a document in a MongoDB collection with an HTTP Put request?

I've recently started working with AngularJS and I encountered an issue while trying to update my MongoDB Database. I'm facing a problem when attempting to update an object within my collection. The code snippet below showcases my approach: //li ...

Passing form data to PHP using AJAX in CodeIgniter Framework

I'm facing an issue with my HTML structure which is as follows: <form method="POST"> Name : <input id="asgname" type="text"> <br> Description : <input id="asgdescription" type="text"> <br> <a href="#" id=" ...