I receive at least 3 types of errors and need to handle them and display corresponding error message. However, when I also check the null or undefined values in the response parameters, my catch block getting a mess and I think there may be a proper way for all of JavaScript applications.
Here is the related catch block that I need to implement properly:
.catch((error) => {
if (error.response?.data?.errors != null && error.response?.data?.errors !== undefined)
error.response?.data?.errors.map((e) =>
enqueueSnackbar(e.field + " " + e.message, { variant: "error" })
);
else if (error.response?.data?.message != null && error.response?.data?.message !== undefined)
enqueueSnackbar(error.response?.data?.message, { variant: "error" });
else enqueueSnackbar(error.message, { variant: "error" });
});
The 3 situations are for example:
-
when there is network problem
-
when API return 500 (bad request)
-
when API return 422 (validation errors)
So, is there a better way to handle these errors in the same catch block?