Search code examples
javascriptjquery

response.message is undefined


I want to get the Error-Message that is currently happening if something is wrong while I fetch. But it just throws out undefined, but the response.message is given as you can see in the Console.

I can't figure out how I can access this Message, can somebody help me?

I tried this way

await fetch(url).then((response) => {
  if (!response.ok) {
    console.log(response.message);
    $("#errorMessage").text("Error " + response.status);
    $(".reload").show();
    return false;
  }
  return response.json();
});

And expected to get this Message:


Solution

  • Clearly you're in an async function, and partly using async/await and partly .then

    this gets messy

    Pick one and stick with it

    Either

    const response = await fetch(url);
    if (!response.ok) {
        const data = await response.json();
        console.log(data.message);
        $('#errorMessage').text('Error ' + response.status);
        $('.reload').show();
        return false;
    }
    return response.json();
    

    Or

    fetch(url)
    .then(response => {
        if (!response.ok) {
            return response.json()
            .then(data => {
                console.log(data.message);
                $('#errorMessage').text('Error ' + response.status);
                $('.reload').show();
                return false;
            });
        }
        return response.json();
    })