A guarantee cannot prevent an error

function grabJSON(url){
    return new Promise(function(successFN, errorFN){
        var request = new XMLHttpRequest();
        request.open('GET', url, true);
        request.responseType = 'json';
        processing(); //trigger special notification
        request.onload = function(e){
            successFN(request.response);
            removeProcessing(); //hide special notification after 'onload'
        };

        request.onerror = function(){
            debugger; //does not execute when URL is incorrect
            errorFN(new Error('Failed to load from: ' + url));
        };

        request.send();
    });
}

However, when I use eventListener - it fails to handle errors:

var previous = document.getElementById('prev');

previous.addEventListener('click', function(){
    grabJSON('http://marsweather.ingenology.com/v1/archive/1').then(function(response){
        debugger; //this works
        console.log(response);
    }).catch(function(err){
        debugger; //this does not work. Why?
        console.log('error occurred ', err);
    });
});

Why is the catch block not working within the eventListener?

UPDATE: Dmitriy Loskutov recommended this - When should XMLHttpRequest's onerror handler fire

Answer №1

It's important to note that the Promise itself is not to blame in this scenario. It is crucial that you properly verify the status within your onload function.

    request.onload = function(e){
        if (request.status === 200) {
            resolveFN(request.response);
        }
        else {
            rejectFN(...);
        }
        removeProcessing(); //this line ensures a specific notification disappears after the 'onload' event
    };

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

Discover the power of the "Load More" feature with Ajax Button on

After browsing through the previous questions and experimenting with various techniques, I've come close to a solution but still can't get it to work. The closest example I found is on Stack Overflow: How to implement pagination on a custom WP_Qu ...

The power of the V8 JavaScript engine: Understanding v8::Arguments and the versatility of function

I have created a Node.js addon that wraps a C++ standard library element std::map<T1,T2>. The goal is to expose this map as a module with two primary functions: Set for adding new key-value pairs and Get for retrieving values by key. I want to create ...

Ways to center vertically aligned buttons within cards in a React application with Material-UI

I've encountered an issue with my ReactJS project using material-ui. I created 3 cards, each with a paragraph of varying lengths. This caused the buttons to be misaligned vertically in each card, as the position differs due to paragraph size differenc ...

Error encountered with AJAX call when attempting to utilize string method

I am looking to add HTML content to a TinyMCE editor in an ASP.NET MVC project. After some thought, I have found a solution that involves converting the HTML file to a string on the server side and then calling it using Ajax on the client side. Here is a ...

Error: The validation of a JSON request failed as schema.validate is not a recognized function

As a beginner, I am currently immersed in a node.js API authentication tutorial. Everything was going smoothly until I had to refactor my code into separate files. Now, every time I send a JSON request via Postman, I keep encountering the error message "Ty ...

Unveiling the Magic: Displaying Quill's raw HTML in Vue.js

Within my Vue.js app, I am utilizing the Quill editor to generate raw HTML content that is saved directly to the database without any cleaning. When fetching this content from the backend, the text and styling are displayed correctly (colors, bolding, etc. ...

Ways to display only a specific color in an image

Looking to work with an image that contains predefined color blocks? Take this example picture as reference: https://i.sstatic.net/QlwvY.png Is there a method to display only certain colored areas while keeping the rest transparent? Note that no edge pat ...

Issue with fitVids() function causing multiple videos to open on a single iframe within a collapsed bootstrap div

Isn't it curious that such a well-known plugin would have this issue? I spent hours trying to figure it out, and eventually succeeded. I believe this post will be very helpful for others who encounter the same problem. Imagine if you have Bootstrap ( ...

Trouble encountered while trying to show information on Tooltip using AngularStrap

I've been attempting to show some information in a Tooltip, but all I see is the Title displayed like this: Below is the HTML code where I'm calling it: <button class="btn btn-primary" type="bu ...

What is the best way to remove a specific HTML section using a JavaScript function?

I am struggling to figure out how to remove a specific HTML section using a button that is contained within the section itself. The section I want to delete was initially added by clicking a different button. Although I can successfully add a new section ...

Why is it that my JQuery sliders appear perfectly fine when viewed locally, but fail to show up when accessed on

I'm facing an issue with two JQuery sliders on my page. The local version works fine, but when I upload it to my web host, only one slider functions correctly. I need both of them to work as intended. Any insights on how to resolve this problem? See ...

I'm having some trouble with jQuery's GET function while working with CodeIgniter. Instead of retrieving a single value, it seems to be returning the source code for a

I have been experimenting with the jQuery GET method, but the results are not what I expected. My goal is to call a function from my controller using jQuery and display the returned value in a specific div within my view. Below you can see the code snippet ...

Transferring the state from a parent component to a child function

I'm having trouble passing a state from a component to a function. I was able to pass the state from Home to ListHome, but I'm struggling to continue passing it to a function within ListHome (Slider) because it's a function. Even after revi ...

Customize the appearance of every other column in an asp gridview

Looking for help with formatting rows and columns in an ASP GridView. The rows are automatically colored alternating, and I want to make the content in every first column bold and every second column normal. I have heard about using CSS nth-child() to achi ...

Interactive audio control with HTML5 and JavaScript technology

I have a vision to enhance my HTML5 based digital comic book for iPad by adding sound effects using a simple play/pause button. Despite spending the entire day experimenting, my limited JavaScript skills are hindering my progress. Here is the link to the c ...

Error message in Vuex4: Unable to access 'state' property because it is undefined

Having trouble with Vue3 and Vuex4, I keep encountering this error: Uncaught TypeError: Cannot read properties of undefined (reading 'state') at ReactiveEffect.eval [as fn] (App.vue?3dfd:36) at ReactiveEffect.run (reactivity.esm-bundler.j ...

Identify and automatically switch to the mobile site following a selection

Seeking a way to incorporate a redirect on my Joomla site that leads users to a mobile-friendly HTML5 app. After much thought, I've put together the following script: <script type="text/javascript> <!-- if (screen.width <= 800) { ...

Update the dropdown choices using an ajax call with mobius1-selectr

Using selectr-master (https://github.com/Mobius1/Selectr) Hello, I'm not sure if I am implementing the correct code to achieve this task. I have 3 dropdowns that need to be populated using jQuery based on a selection made in another dropdown. I am at ...

What is the best way to activate Bootstrap's tooltip functionality following its inclusion via AJAX?

One of the features I am adding to my website using ajax is a tooltip. The snippet looks like this: <a href="#" data-toggle="tooltip" title data-original-title="My tooltip text...">Hover me...</a> To get it to work, I need to initialize it as ...

Utilizing a self-invoking function to incorporate JavaScript

In my role, I am responsible for managing a Content Management System (CMS) used by developers to create content that involves JavaScript. In the past, we placed the content in an iFrame for containment purposes; now, it operates as a single-page client-si ...