I'm fetching an API that returns a json but when it has an error, it returns only a text (In node with express, results are returned with .json({}) and errors with .send('string')), but I can't modify the API.
So I'm trying to make something that reads the json, but if it's an text, it will go in .catch where the error is the text.
Here is what I have tried but with no success:
fetch(apiUrl)
.then(res => {
try {
let json = res.json()
return json
} catch (error) {
return new Promise((resolve, reject) => reject(res.text()))
}
})
.then(res => {
// get result from res.json() **res == res.json**
})
.catch(error => {
// get result from res.text() **res == res.text**
})
How can I achieve this? How to get res.json() in the next .then() but if it fails, get res.text() in the .catch?
Edit: I want to get the .text in .catch. I don't know why, but throwing res.text() doesn't work.