for example I am calling an api to register an user, I am already validating in client side before call the API,
after calling api, server side will validate also, like (email already exists or phone number not valid or confirm password are not matching)
In server side I return custom error with Status code and error message like below
return StatusCode(451, "Email ID already exists");
once received the above error from Server side to Axios Interceptor
axios.interceptors.response.use(function (response) {
//...
return response;
}, function (error) {
// Any status codes that falls outside the range of 2xx cause this function to trigger
//here I am receiving error = Email ID already exists
return Promise.reject(error);
});
If i make return Promise.reject(error);
, it throws error in console log ,
If I make return error
, this is returning to AddUser -> response
not to catch
then I can catch error in my axios post request catch
async function AddUser(user) {
try {
const response = await axios.post("/Auth/register", user)
console.log(response)
} catch (error) {
console.log(error.response.status) // 451
console.log(error.response.data) // Email ID already exists
return await Promise.reject(error) // again console log get error
}
}
The above adduser
is also a function, which is calling from useMutation
using React-Query
export const apiAuthRegister = ({onError}) => {
const navigate = useNavigate();
return (
useMutation({
mutationKey: ['authRegister'],
mutationFn: (user) => AddUser(user),
onSuccess: (data) => {
//....
},
onError: (error) => {
console.log('REGISTER FAILED')
console.log(error) // Email ID already exists
onError(error.response.data) // this is callback function, will update the error in TextBoxField error message
}
})
)
}
Is this a way to handle Server side custom error?
or I should receive as a response (ex: Status code: 151), then pass it to -> axios response -> useMutation
UPDATE
Can I store these axios Interceptor error to Redux Store as a error-slices, and directly use it wherever I wants to get update? Instead of
return error
orreturn Promise.reject(error)
from AxiosInterceptor to AxiosCall, then again AxiosCall to useMutation, then again from useMutation to update State variable
Is it really good approach?
Thanks in advance