1

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?

Community
  • 1
  • 1
  • .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 '16 at 09: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 '16 at 09: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 '16 at 09:27

1 Answers1

1

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

Aleksey L.
  • 35,047
  • 10
  • 74
  • 84
  • 1
    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 '16 at 11:24