Is it possible to get the text value of a response if the json decoding fails?
I have the following code:
try {
var response = await fetch(url, options);
var data = await response.json();
// do stuff
}
catch(error) {
var text = await response.text(); // TypeError: Failed to execute 'text' on 'Response': body stream already read
}
This sometimes happens if the server is down or the network is offline.
I’m realizing it makes the response.json()
function useless because if I have errors I’ll always need to get the text value.
Currently the error is:
SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
Ignore the error above and please let me know if there is a way to get the text value from the response after I call json()
.
It seems to me that if the method to convert the response to json using the response.json()
method fails it should allow you to get the text value. Does that make sense?