0

In Thunk function I'm doing post http request, and in case of error I want to handle it => show messsage from server to user, like email already exist or else. But how do I properly define type of error in try{}catch{} syntax. With following code I have error in terminal enter image description here

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import axios from "axios";
import { FormSignUp } from '../../types/FormSignUP';

export const signupUser = createAsyncThunk('user/signupUser', async (user: FormSignUp) => {
  try {
    const response = await axios.post(API_URL, user);
    return response.data
  } catch (err: Error) {
    console.log(err.response.data)
  }
});

I understand that proper type of err in axios request is AxiosError. But with next code is another error.

import axios, { AxiosError } from "axios";

export const signupUser = createAsyncThunk('user/signupUser', async (user: FormSignUp) => {
  try {
    const response = await axios.post(API_URL, user);
    return response.data
  } catch (err: AxiosError) {
    console.log(err.response.data)
  }
});

and here is an error enter image description here

Edited: So, this kind of works.

try {
    const response = await axios.post(API_URL, user);
    return response.data
  } catch (err) {
    if (axios.isAxiosError(err) && err.response) {
      console.log( err.response.data);
    }
  }

1 Answer 1

2

Typescript 4.0 added the ability to specify unknown and any on-catch variables (Issue) it can not do typecasting inside catch.

With this flag, the following is now possible:

Reference this

instead of this:

try {
    const response = await axios.post(API_URL, user);
    return response.data
} catch (err) {
    if (axios.isAxiosError(err) && err.response) {
      console.log( err.response.data);
  }
}

You can do this

try {
    const response = await axios.post(API_URL, user);
    return response.data
} catch (_err) {
   let err = (_err as AxiosError)
   // and you now got the error type
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.