Capacitor community http handle errors

I often use Axios to perform requests in my applications, however due to incompatibility with iphone, I had to use the capacitor-community/http library, however the try catch blocks are always returning success, even if there was an error in the request. How can I handle errors using this library?

try {
        await Requester.auth.public.login(formData);
       
          this.$store.dispatch('login', user);
          this.$root.$emit('showToast', {
            text: 'Seja bem vindo!',
            color: 'success',
          });
          this.$router.push({ name: 'Cotacao' });
   
      } catch (err) {
        this.$root.$emit('showToast', {
          text: err.response?.data ?? err.toString(),
          color: 'error',
        });
      } finally {
        this.loading.submitForm = false;
      }
    },

My request

const login = async (formData: AuthLoginFormData): Promise<User> => {
  const res: HttpResponse = await Http.post({
    url: `${BASE_URL}public/auth/login`,
    headers: {
      'Content-Type': 'application/json',
    },
    data: formData,
    webFetchExtra: {
      credentials: 'include',
    },
  });

  return res.data;
};
1 Like

I just started doing this too.

In my case, I manually throw the errors in the response:

    return (Http.request(options).then((response) => (
      handleResponse(response)
    )).catch((error) => {
      console.log('postError', error, error.message);
     }));

const handleResponse = (
  response: HttpUploadFileResult | AxiosResponse<unknown>,
) => {
  // @ts-ignore
  if (response.error) {
    console.log('error', response.data);
    throw new Error(response.data);
  }
  // No error, continue processing...
};

This works but it’s a little ugly. There’s probably a better way.

Thanks, I will try it!