12
votes

I'm using blob responseType with Axios in my VueJS app for downloading a document from the server. When the response code is 200 it works fine and download the file but when there is any http error, I'm not able to read the status code when I catch the error because the error is a JSON response.

Has anyone had a similar issue and worked out a way to convert the blob response type to json and thrown an error based on the status code?

I have tried sending the response as a plain text from Laravel backend and tried converting the response to JSON or text in the front-end but no luck.

I have tried reading error response headers but no luck.

Axios({
        url: 'xxxx',
        method: 'GET',
        responseType: 'blob', 
        })
    .then((response) => {
        //code to read the response and create object url with the blob and download the document
    })
    .catch((error) => {
      console.log('Error', error.message); //nothing
      console.log('Error', error.error); //undefined
      console.log('Error', error.data); //undefined

      const blb    = new Blob([error], {type: "text/plain"});
      const reader = new FileReader();

      // This fires after the blob has been read/loaded.
      reader.addEventListener('loadend', (e) => {
        const text = e.srcElement.result;
        console.log(text);
      });
     // Start reading the blob as text.
     reader.readAsText(blb);
});

I just want to throw the error message based on the status code. If it's 401 just want it to be unauthorized and anything else throw it on to the component.

4
@tony19 nothing about blob in the question you mentioned.Tarasovych
@Tarasovych The responseType field has no bearing on the status code, which is accessed the same way regardless.tony19
You may find this helpful: Error Response for blob type. It's a similar issue with several solutions.ChewySalmon

4 Answers

1
votes

You need to convert the response blob to json:

Axios({
    url: 'xxxx',
    method: 'GET',
    responseType: 'blob',
  })
  .then((response) => {
    //code to read the response and create object url with the blob and download the document
  })
  .catch((error) => {
    if (
      error.request.responseType === 'blob' &&
      error.response.data instanceof Blob &&
      error.response.data.type &&
      error.response.data.type.toLowerCase().indexOf('json') != -1
    ) {
      new Promise((resolve, reject) => {
          let reader = new FileReader();
          reader.onload = () => {
            error.response.data = JSON.parse(reader.result);
            resolve(Promise.reject(error));
          };

          reader.onerror = () => {
            reject(error);
          };

          reader.readAsText(error.response.data);
        })
        .then(err => {
          // here your response comes
          console.log(err.response.data)
        })
    };
  });

For more info

1
votes

The reason is that the response type is blob.
In case of error, the status code is available directly in your exception object. However, the response is a promise.

What you need to do is:

.catch((error) => {
    let statusCode = error.response.status
    let responseObj = await error.response.data.text();
       :
       :

For more details you can read documentation.

0
votes

I believe you might be using the error variable in your catch() incorrectly.

Axios passes an error object that has a response property that is where you will want to look for your error or message.

https://github.com/axios/axios#handling-errors

On a side note if you can catch the error server side you could try setting the Content-type header to text/plain. Using either header('Content-Type: plain/text') or Laravel's Response Methods

0
votes
use err.response.status
     Axios ({ 
        url: 'xxxx', 
        method: 'GET', 
        responseType: 'blob', 
        }) 
    .then ((response) => { 
        // code pour lire la réponse et créer l'URL de l'objet avec le blob et télécharger le document 
    }) 
    .catch ((error) => { 
      console.log ('status', error.response.status); 
 ; 
 
});
    ```