Is there a way to capture an error message in the JSON fetch response?

Here is the code snippet to consider:

fetch('https://api.flickr.com/services/rest/?method=flickr.photos.search' +
    '&api_key=thiskeyshouldgivemeanerror&text=dog&format=json' +
    '&per_page=24&nojsoncallback=1')
    .then(function(rsp) {
        // The response shown in the first console.log does not match my expectations
        console.log(rsp);
        if(rsp.stat !== "ok") {
            throw new Error(rsp.message);
        }
        else {
            return rsp.json();
        }
    })
    .then(function(rsp) {
        // Here's the output I'm looking for: "{stat: "fail", code: 100, message: "Invalid API Key (Key not found)"}"
        console.log(rsp);
    })
    .catch(function(err) {
        alert("Encountered an issue. " + err);
    });

I am attempting to catch any errors and display the corresponding JSON error message from the response. However, the format of the response differs between the two console.logs. How can I ensure the response matches my expectation from the start?

In addition, why does the initial response show "ok" despite the absence of a valid API key?

Lastly, what is the reason behind needing to call rsp.json() to retrieve the correct JSON data in the second instance when it should have already been in JSON format?

Answer №1

Remember that the rsp in the first then-block is a response object, not the actual data from the backend. Since the response object doesn't contain a stat field, it cannot be "ok". You should instead check for rsp.ok or rsp.status.

For more information, you can refer to the response object reference

In the second then-block, make sure to validate the JSON data received from the backend before proceeding. If necessary, throw an error based on the checks.

fetch(url)
  .then(function(response) {
    if(!response.ok) {
      throw new Error("not ok");
    }
    return response.json()
  })
  .then(function(result) {
    if(result.stat === "fail") {
      throw new Error(result.message);
    }

    // Process the result when everything is okay

  })
  .catch(function(err) {
    alert(err);
  });

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

The data from Ajax response is not showing up on the datatable when accessed through Firefox and Edge browsers

I am facing an issue where my report displays correctly on Google Chrome, but when I try to view it on Firefox or Edge browser, the JSON response is shown on the browser instead of the data table. A sample response is shown below: " [{\"RegisteredBy ...

The AngularJS asynchronous directive in isolation is malfunctioning

I need to pass an object retrieved from the database to a child directive. Sending data synchronously works fine, but when I fetch the data asynchronously from a remote server, the directive is triggered before the results are received. Here is the contro ...

Limit the length of text using jQuery by specifying the maximum pixel width

Trying to utilize jQuery for a quick function that calculates the pixel width of a string on an HTML page and then shortens the string until it reaches a desired pixel width... Unfortunately, I'm encountering issues with this process as the text is n ...

After the "div" tag comes the magic of AJAX, PHP, and JAVASCRIPT, replacing

My Ajax implementation is successfully displaying the selected content on a div, but unfortunately, everything that comes after the div is getting replaced by this output. I am unsure of why this is happening and how to resolve it. If you have any insigh ...

Searching for values within a JSON array in Postgresql using wildcard characters and comparison operators, while taking advantage of indexing

I am working with a table containing JSON array data that I need to search through. CREATE TABLE info (id SERIAL, content JSON); INSERT INTO info (id, content) VALUES (1, '[{"name": "Info A", "value": 10}]'); INSERT INTO info (id, content) ...

Quickly align with vertices using threejs

As I delved into creating a snapping feature to align with my mesh vertices, I embarked on multiple trial-and-error solutions. One method involved introducing THREE.Sprite instances for each vertex in the scene and utilizing a rayCaster to determine if th ...

What is the best way to switch the CSS style of a button that has been mapped

I'm currently working on toggling the CSS class for an individual button that is created from a mapped array. Although my code is functional, it toggles the CSS class for all buttons in the mapped array instead of just the one selected. ...

Example using Three.js Collada: "file is either empty or does not exist"

I am currently troubleshooting the Three.js Collada loader example. I have successfully run other samples, including the .obj loader and blender scene, by running a local http server to load images for textures and models. However, when attempting to run t ...

What could be the reason my Backbone view is failing to render?

Can anyone help me troubleshoot why this template isn't rendering properly in my backbone views? Any insights would be greatly appreciated! Below, I've included the code from my jade file for the views and the main.js file for the backbone js scr ...

changing an array into json format using TypeScript

Looking to convert an array into JSON using TypeScript. How can I achieve the desired result shown below? let array = ['element1', 'element2', 'element3'] result = [{"value": "element1"}, {"value": "element2"}, {"value": "el ...

Guide to utilizing a web worker from an npm package in your primary webpack application

My project is structured in the following way: moduleA -> Library that I publish to npm using Rollup projectA -> My Gatsby project that installs moduleA and utilizes it. To bundle my workers with other library code into the dist folder, I am using ...

How to modify ID data with AngularJS ng-repeat

I am currently searching for a solution to easily modify an ID within a repeated ng-structure. This scenario involves having a customer table with unique customer IDs, which are then utilized in another table related to orders. When I retrieve data from th ...

How can I ensure that a pop-up is shown only once per day in Vue.js

I am facing an issue with a method that is supposed to display a modal window 4 seconds after the user logs onto the website. If the modal is closed, it should not be displayed again for the next 24 hours. However, I am encountering problems with LocalSt ...

managing commitments in TypeScript

Is there a way to convert a promise into a string, or is there another method for handling this result? I am encountering an error stating "You cannot use an argument of type 'Promise' for a parameter of type 'string'." const pokemonIma ...

Substitute the attributes of one object with those of another

Alright, I'm revising this because it seems to be causing confusion. Imagine you have two items x and y. What I aim to do is swap all the characteristics of x with those of y. (Please note that this isn't your usual duplication process where a ...

Why is "undefined" being used to alert an ajax call response?

I am encountering an issue with a returned value from an AJAX request. The web method being referenced returns a boolean value of true or false. However, when attempting to access this value outside the AJAX method, I am receiving an "undefined" message :? ...

Identifying changes in data streams

I am attempting to update the value of a div when the data attribute of another div changes. This is my code: $('.language-rate').attr("data-rate-value").on('change', function () { $('.language-d').text($('.language- ...

Inject the contents of an HTML file into a Vue div

Currently, I am utilizing jsfiddle to go through THIS {{respondedText}} <div>{{respondedText}}</div> But let's say I want to import HTML content from a file or website and then place it inside that div instead of showing "Event Rec ...

What is the reason for the lack of uniqueness in Mongo ObjectIDs?

As per the documentation available from MongoDB, ObjectID's are supposed to be generated using a specific format: An ObjectID is a 96-bit number consisting of: a 4-byte timestamp representing seconds since the Unix epoch (up until the year 2106) a ...

Creating various designs utilizing shared components through inheritance

I've spent a considerable amount of time researching this issue but have yet to come across a satisfactory solution (perhaps because I haven't formulated my question clearly). Nevertheless, here we are... I need to create two data structures base ...