I’m developing a react app. I’m trying to catch an error and bubble it up to my ErrorBoundary component. The ErrorBoundary component is the direct parent of the component where I’m sending the request. I’ve tested throwing a random error just to test if the ErrorBoundary would catch it and it does, everything works fine. The problem arises with the fetch request, I can’t seem to catch the error. This is the code:
const onSubmit = async (data) => {
const eventData = {
firstName: data.firstName,
lastName: data.lastName,
username: data.username,
email: data.email,
password: data.password,
};
try {
const response = await fetch(
"https://localhost:7182/api/v1/users/create",
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(eventData),
}
);
if (!response.ok) {
const responseError = await response.json();
const code = responseError.ErrorCode;
if (response.status === 409) {
if (code === emailAlreadyExists) {
setError("email", {
type: "server",
message: serverErrors[code],
});
} else if (code === usernameAlreadyExists) {
setError("username", {
type: "server",
message: serverErrors[code],
});
}
}
} else if (response.ok) {
navigate("/home");
}
} catch (error) {
throw error;
}
};
Does anyone have an idea why doesn’t it catch the error? All I get in the chrome’s console is "
Uncaught (in promise) TypeError: Failed to fetch
at onSubmit…
error. Thank you for your time.
2
Answers
So after many failed tries, I ended up coming up with the solution of just redirecting the user to the error page of my application directly when I catch the error, ignoring the errorBoundary component. The code that I changed:
EDIT: after some research, I discovered that the main reason I'm not being able to catch the error (after throwing it) is because these components (i.e. the ErrorBoundaries) DO NOT catch errors from asynchronous calls (such as my case). Moreover, they do not catch errors from: SSR, error boundaries (themselves) and event handlers.
True, your throwing a new error… But also with promises (that’s what fetch returns – a promise) you can catch the ‘error’ (the rejection of the promise) like this too: