Reputation: 2155
Using javascript fetch and invoking a rest service that returns a blob if successful, otherwise returns an error message as json. How would this be handled in the fetch? The actual service is a asp.net web api implementation that returns a FileStreamResult (or FileContentResult) when successful, otherwise returns an error code with json containing the error message. Below is an example of what I'm trying to do:
fetch('flowers.jpg').then(function(response) {
if(response.ok) {
return response.blob();
} else {
return response.json();
}
}).then(function(myBlob) { // here I would also like to function(jsonError)
var objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
}).catch(function(error) {
console.log('There has been a problem with your fetch operation: ', error.message);
});
Upvotes: 11
Views: 25045
Reputation: 4830
You can use nested then block to pass literally whatever you want to your next then handler. Sample:
fetch('flowers.jpg').then(function (response) {
if (response.ok) {
return response.blob()
.then(function (myBlob) {
return {
blob: myBlob
};
});
} else {
return response.json()
.then(function (myJson) {
return {
json: myJson
};
});
}
}).then(function (myData) {
if(myData.blob){
// Handle blob case
}else{
// Handle JSON case
}
}).catch(function (error) {
console.log('There has been a problem with your fetch operation: ', error.message);
});
Perhaps a more semantically accurate way of handling this is rejecting when there is an error.
fetch('flowers.jpg').then(function (response) {
if (response.ok) {
return response.blob();
} else {
return response.json()
.then(function (myJson) {
return Promise.reject(myJson);
});
}
}).then(function (myData) {
// Handle blob case
}).catch(function (error) {
//Handle JSON case
});
Upvotes: 2
Reputation: 1075199
Since you want to go down two fairly different paths, this is one of the relatively-rare situations where you probably want to nest handlers:
fetch('flowers.jpg').then(function(response) {
if (response.ok) {
return response.blob().then(function(myBlob) {
var objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
});
} else {
return response.json().then(function(jsonError) {
// ...
});
}
}).catch(function(error) {
console.log('There has been a problem with your fetch operation: ', error.message);
});
Upvotes: 19