Developing a method to handle HTTP errors when utilizing the fetch method to retrieve data from an API endpoint

// GitHub users
document.getElementById('btn3').addEventListener('click', fetchData);
// Fetching from external API
function fetchData() {
    fetch('https://api.github.com/users')
        .then(function (res) {
            console.log(res.ok); //true
            return res.json();
        })
        .then(handleErrors)
        .then(function (users) {
            let output = '';
            users.forEach(user => output += `<li>${user.login}</li>`);
            document.getElementById('output').innerHTML = output;
        })
        .catch(function (err) {
            console.log(err);
        });
}

// Handling fetch HTTP errors
function handleErrors(res) {
    if (!res.ok) throw new Error(res.error);
    return res;
}

Output in developer console:

true
app.js:55 Error
    at handleErrors (app.js:61)

If I modify my handleErrors function to this:

function handleErrors(res) {
    if (!!res.ok) throw new Error(res.error);
    return res;
}

Then it works as expected

Questions:

  1. What's the issue with my implementation of the handleErrors function?
  2. What does the !! operator do?
  3. Where can I find good resources to learn asynchronous programming, specifically AJAX?

Answer №1

  1. It is crucial to handle error input arguments as arrays, not just the res received in the first "then" block since you are returning res.json().

  2. The reason for this is that within the error handler, res.ok is undefined, resulting in !!undefined evaluating to false.

  3. GIYF (Google is your friend).

Hope this information proves helpful. ;)

Additional notes:

  1. If the fetch operation encounters an error, it will directly move to the catch function, eliminating the need to check res.ok.
  2. Adhering to the single responsibility principle is essential. Each function should have a specific purpose. This approach enhances readability and maintainability.
function getExternal() {
    return fetch('https://api.github.com/users')
        .then(function (res) {
            return res.json();
        });
}

function modifyDOM (users) {
    let output = '';
    users.forEach(user => output += `<li>${user.login}</li>`);
    document.getElementById('output').innerHTML = output;
}

function run() {
    getExternal()
        .then((users) => modifyDOM(users))
        .catch(function (err) {
            console.log(err);
        });
}

// Alternatively, use its point-free version
// function run() {
//     getExternal()
//         .then(modifyDOM)
//         .catch(console.log);
// }

run();

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

iOS devices featuring the scroll function allows for seamless navigation and effortless

Here is the code snippet that I am using: $(document).scroll(function() { thedistance(); }); I would like thedistance() to trigger while a user is scrolling on an iOS device, however, it currently only fires after the scrolling has stopped, rather t ...

Understanding the importance of maintaining the execution order is crucial when working with NodeJS applications that utilize

Can someone please assist me in understanding how to solve this issue? This snippet is from my auth-routes.js file: const userControllers = require('../controllers/user') module.exports = function(app){ app.post('/auth/recuperarpassword& ...

What are examples of CPU-intensive tasks, such as sorting and searching, that require significant processing power?

When it comes to defining a CPU intensive task in terms of an algorithm or code rather than a specific use case like video editing, what exactly falls into that category? For instance, is sorting, searching, graph traversal, matrix multiplication conside ...

Having trouble importing a CSS file into a Vue.js single file component?

I am attempting to include 2 CSS files within the style tag of my Vue.js single-file component. <style > @import '../assets/styles/jquery-ui.js.css'; @import '../assets/styles/jquery-ui.css'; </style> However, I am ...

Adjust the x and y coordinates of the canvas renderer

Manipulating the dimensions of the canvas renderer in Three.js is straightforward: renderer = new THREE.CanvasRenderer(); renderer.setSize( 500, 300 ); However, adjusting the position of the object along the x and y axes seems more challenging. I've ...

Turn off pagination for tables in Material-UI

Currently, I am utilizing the TablePagination component from Material-UI in my React project. Unfortunately, this component does not come with a built-in disabled prop. I do have a boolean variable called loading that I would like to utilize as a paramet ...

The 'disabled' property is not found in the 'MatButton' type, however, it is necessary in the 'CanDisable' type

Issue found in node_modules/@angular/material/core/option/optgroup.d.ts: Line 17: Class '_MatOptgroupBase' does not correctly implement interface 'CanDisable'. The property 'disabled' is missing in type '_MatOptgroupBas ...

Limit the number of ajax requests that can be initiated to once, similar to a button click

I have a like button that, when clicked, increments a value in my database table by 1. Upon clicking the button: var button_id = $(e.target).closest('div').attr('id'); var id = button_id.substring(12); $.ajax({ method: &apos ...

What is the best way to allow a container div to only show horizontal overflow, without relying on "display:inline-block" for its inner divs?

My coding challenge involves dynamically creating nested <div> elements within another <div> when a button is clicked. Upon clicking the button, a new inner <div> with a unique id is generated inside the outer <div>, each possessing ...

Unlocking the Power of Django with Ajax and Facebook API: Conquering the 403 Forbidden

I'm attempting to integrate the Facebook Login API into my Django project. My initial plan was to use a Facebook username and a default password (since Django requires a password for user creation) and authenticate via AJAX. FB.api('/me', ...

The inability for two dynamically created Ajax elements to identify one another is hindering their interaction

Hello wonderful people at Stack Overflow, I've been attempting to create a table generator that dynamically creates two tables upon the click of a button. So far, it's been quite a frustrating journey full of roadblocks... Currently, my approac ...

accessing PHP variables within JavaScript code

My file has a .php extension. I have a php variable called $dataSelected which is an associative array. This variable represents the result set of a select query output. When I print it using print_r, here is what it looks like: Array ( [0] => Array ...

Ajax mode in Mvcpaging is malfunctioning

Having some trouble with getting MvcPaging to work in Ajax mode. It seems that it's not behaving as expected - instead of making an Ajax call, it's doing a full GET request. When checking the controller code, I noticed that Request.IsAjaxRequest( ...

Error message: Unable to locate module (webpack)/hot/emitter when running ionic serve with Ionic 4

Current Technology Stack: Node v10.15.1 Ionic 4.10.1 Upon running ionic serve, an error is encountered: ERROR in (webpack)/hot/emitter.js [ng] Module not found: Error: Can't resolve 'events' in '/zazou/node_modules/@angular-de ...

NodeJS: Issue when implementing try/catch with async/await causing SyntaxError

As a newcomer to Node Js, I am struggling to understand why the code below is throwing a syntax error with catch(). I recently updated to Node JS V14. Any assistance would be greatly appreciated. async function demoPromise() { try { let message ...

Ways to resolve the issue of the 'setConfirmDelete' property not being found on type 'JSX.IntrinsicElements' in React.js

index.tsx const setConfirmDelete = (state, close) => { return ( <Modal show={state} onHide={close}> <Modal.Header> <Modal.Title>Title</Modal.Title> </Modal.Header> <Modal.Body> 'T ...

Convert a JavaScript object into a serialized form

Alright, so here's the thing that's been bugging me. I have this JavaScript object that I need to pass to a PHP script using jQuery AJAX. But every time I try to pass it as is, I get an error. It seems like the object needs to be serialized befor ...

Using Node.js to retrieve JSON objects from an API call with node-postgres

After carefully following the instructions on connecting to my postgres table using async/await provided at , I have successfully set up routes to retrieve and display user data. By accessing localhost:3000/users/1, the browser displays the JSON string fo ...

Unable to dismiss message in Django

I'm a beginner in Django and I recently followed a tutorial to add message alerts to my code. The alerts are displaying correctly, but unfortunately, I am having trouble closing them using the 'x' button. https://i.stack.imgur.com/BQS1S.png ...

Looking to substitute the <mark> element within a string with the text enclosed in the tag using JavaScript

In need of help with replacing tags inside a string using JavaScript. I want to remove the start and end tags, while keeping the content intact. For example, if my input string is: <div class="active"><mark class="active-search-position">The ...