-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Advanced React] Error Handling #100
Comments
Production Levels TipsError Management User Experience
Error on visiting Page
Error that caught by ErrorBoundary
The widely used solution is react-error-boundary. Bellow is a sample code import { ErrorBoundary, type FallbackProps } from 'react-error-boundary';
// some other code
<ErrorBoundary
fallbackRender={(props) => <ErrorFallback {...props} />}
onError={(error) => {
/*
log error to the server here
*/
}}
>
<Suspense fallback={<Loading />}>
<Outlet />
</Suspense>
</ErrorBoundary> |
Handle Axios ErrorThe best practices of applying
export class HttpError extends Error {
cause: string;
static RESOURCE_NOT_FOUND = 'RESOURCE_NOT_FOUND';
static TIMEOUT = 'TIMEOUT';
static NETWORK_ERROR = 'NETWORK_ERROR';
static SERVICE_UNAVAILABLE = 'SERVICE_UNAVAILABLE';
constructor(message: string, cause: string) {
super(message);
this.cause = cause;
}
}
this.clientInstance.interceptors.response.use(
(res) => res.data,
(error: AxiosError<BackendError>) => {
if (!error) {
return Promise.reject(new Error('Unknown error occurred.'));
}
if (error.code === 'ECONNABORTED') {
return Promise.reject(
new HttpError('Request timed out.', HttpError.TIMEOUT)
);
}
if (error.code === 'ERR_NETWORK') {
return Promise.reject(
new HttpError(
'Network error occurred. Please check your internet connection.',
HttpError.NETWORK_ERROR
)
);
}
if (error.response && error.response.status >= 500) {
return Promise.reject(
new HttpError(
'Service unavailable. Please try again later or contact support.',
HttpError.SERVICE_UNAVAILABLE
)
);
}
if (error.response && error.response.status === 404) {
return Promise.reject(
new HttpError('Resource not found.', HttpError.RESOURCE_NOT_FOUND)
);
}
const { message: axiosMessage, response } = error;
const { status, data } = response ?? {};
let errorMessage = axiosMessage;
if (status === 401) {
HttpClient.removeAccessToken();
toast.error('Your session has expired. Please log in again.');
setTimeout(() => {
window.location.reload();
}, 2500);
return;
}
errorMessage = data?.message ?? axiosMessage ?? 'Unknown Error.';
return Promise.reject(new Error(errorMessage));
}
);
// The eror data format designed with backend
interface BackendError {
} Designed logic as above, as there are cases we want to handle |
Overview
This article is a reading note of the error handling chapter from <<Advanced React>>, together with some of my practices.
Best Practices
The text was updated successfully, but these errors were encountered: