skip to Main Content

I want to analyse anwser from http request, display error if needed then return data.

This is what I’m doing right now:

fetch(URL,{method:"GET"})
.then(async response => { await read_errors(response) })
// .then(response => { read_errors(response) }) (Both had been tried)
.then( function(data) { 
    doSomething(data)
})
.catch( error => { display_error(error) })

With this function :

async function read_errors(response) {
    const isJson = response.headers.get('content-type')?.includes('application/json');
    const data = isJson ? await response.json() : null;

    const isText = response.headers.get('content-type')?.includes('text/');
    const text = isText ? await response.text() : null;

    // check for error response
    if (!response.ok) {
        // get error message from body or default to response status
        const error = (data && data.message) || text || response.status;
        console.error("Something went wrong : ",error)
        return Promise.reject(error);
    } else {
        fckng_response = isJson ? data : text
        return Promise.resolve(fckng_response)
    }
}

But I’ve got TypeError: data is undefined

The answer from server is all right with headers and data OK.

What am I doing wrong?

2

Answers


  1. You’re not returning the result of calling read_errors in the .then callback. Either add a return statement or remove the braces ({}).

    .then(response => read_errors(response))
    // no need for async here
    

    It is simpler to completely work with async and await, without mixing it with callbacks.

    try {
        const response = await fetch(URL);
        const data = await read_errors(response);
        doSomething(data);
    } catch (error) {
        display_error(error);
    }
    
    Login or Signup to reply.
  2. To fix this issue, you need to return the data from the read_errors() function. Here’s the modified code:

    fetch(URL, { method: "GET" })
      .then(response => read_errors(response))
      .then(data => {
        doSomething(data);
      })
      .catch(error => {
        display_error(error);
      });
    
    async function read_errors(response) {
      const isJson = response.headers.get('content-type')?.includes('application/json');
      const data = isJson ? await response.json() : null;
    
      const isText = response.headers.get('content-type')?.includes('text/');
      const text = isText ? await response.text() : null;
    
      if (!response.ok) {
        const error = (data && data.message) || text || response.status;
        console.error("Something went wrong:", error);
        throw error; // Use throw instead of Promise.reject
      } else {
        const fckng_response = isJson ? data : text;
        return fckng_response;
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search