axios cancellation caught inside of then() instead of catch()

4.8k views Asked by At

I making a multi-upload file form.

Upon user cancellation, once the corresponding axios call get cancelled using cancel(), I having a weird behaviour. My axios call get caught inside the then() whereas it should be caught inside of catch(). The response inside of then() returns undefined.

I am having a hard time figuring if I did something wrong on the front-end part, I think my call is may be missing some headers or maybe it's on the backend part ?

      const payload = { file, objectId: articleId, contentType: 'article' };

      const source = axios.CancelToken.source();

      // callback to execute at progression
      const onUploadProgress = (event) => {
        const percentage = Math.round((100 * event.loaded) / event.total);
        this.handleFileUploadProgression(file, {
          percentage,
          status: 'pending',
          cancelSource: source,
        });
      };

      attachmentService
        .create(payload, { onUploadProgress, cancelToken: source.token })
        .then((response) => {
          // cancelation response ends up here with a `undefined` response content
        })
        .catch((error) => {
          console.log(error);
          // canceled request do not reads as errors down here
          if (axios.isCancel(error)) {
            console.log('axios request cancelled', error);
          }
        });

the service itself is defined below

export const attachmentService = {
  create(payload, requestOptions) {
    // FormData cannot be decamelized inside an interceptor so it's done before, here.
    const formData = new FormData();
    Object.entries(payload).forEach(([key, value]) =>
      formData.append(decamelize(key), value),
    );
    return api
      .post(resource, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        ...requestOptions,
      })
      .then((response) => {
        console.log(response, 'cancelled request answered here as `undefined`');
        return response.data;
      })
      .catch((error) => {
        // not caught here (earlier)
        return error.data;
      });
  },
};

cancellation is called upon a file object doing

file.cancelSource.cancel('Request was cancelled by the user');
1

There are 1 answers

0
petitkriket On BEST ANSWER

As suggested by @estus-flask in a comment, the issue is that I was catching the error inside of the service (too early). Thank you!

export const articleService = {
  create(payload, requestOptions) {
    // FormData cannot be decamelized inside an interceptor so it's done before, here.
    const formData = new FormData();
    Object.entries(payload).forEach(([key, value]) =>
      formData.append(decamelize(key), value),
    );
    return api.post(resource, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      ...requestOptions,
    });
  },
};