Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

I ran into an issue with $http called with responseType: blob. I would like to handle errors response in JSON but I get blob data instead even if I set the response's content-type as 'application/json' on the server.

$http.post(url, data, {responseType: 'blob'})
  .then(function(response) {
    // download the file  (works fine)
  })
  .catch(function(error) {
    // handle JSON response error
  });

Is there any way to do that without trying to convert error data to object?

share|improve this question
    
.then() function can be used in a more efficient manner... .then(function(response){},function(error){ console.log(error);}); In the console.log() you will get it in the manner you want it to. and then you can handle it. – Tirthraj Barot Jun 16 at 9:03
    
Thanks but the convention on my project is to use then().catch() instead of then(onSuccess, onError). Unfortunately it doesn't change the fact that the data in the onError callback remains blob type. – Samuel Martineau Jun 16 at 9:24
    
can you try $http({method: 'GET', url: Restangular.one('attachments', idAtt).getRestangularUrl(), headers: {'X-Auth-Token': token}, responseType: 'blob'}).then(function(response) { var url = (window.URL || window.webkitURL).createObjectURL(response.data); window.open(url); }); – Tirthraj Barot Jun 16 at 9:27
up vote 0 down vote accepted

You can't have different content types for success and error cases, but you can manage conversion in single place. Write responseError interceptor where you can check if error.data is instanceof Blob and convert it to JSON

share|improve this answer
    
Hi Aleskey, I've already fixed it with an interceptor and readAsText method of FileReader but I was wondering if there's a more elegant way to do that. – Samuel Martineau Jun 16 at 11:24

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.