The error to handle.
The converted AppError object.
export function handleNetworkError(error: unknown): AppError {
// Handle fetch errors and timeouts
if (
error instanceof TypeError &&
(error.message.includes("fetch") || error.message.includes("network"))
) {
return createError(
ErrorType.NETWORK,
"Unable to connect to the server. Please check your internet connection.",
error,
"NETWORK_UNAVAILABLE",
);
}
// Handle API responses with error status codes
if (
error instanceof Response ||
(typeof error === "object" && error !== null && "status" in error)
) {
const response = error as
| Response
| { status: number; statusText?: string };
const status = response.status;
const message = "An error occurred while communicating with the server.";
const code = "API_ERROR";
if (status === 401 || status === 403) {
return createError(
ErrorType.AUTH,
"Authentication failed. Please log in again.",
error,
"AUTH_FAILED",
);
}
if (status === 404) {
return createError(
ErrorType.SERVER,
"The requested resource was not found.",
error,
"NOT_FOUND",
);
}
if (status >= 500) {
return createError(
ErrorType.SERVER,
"The server encountered an error. Please try again later.",
error,
"SERVER_ERROR",
);
}
return createError(ErrorType.SERVER, message, error, code);
}
// For timeout errors
if (error instanceof Error && error.name === "TimeoutError") {
return createError(
ErrorType.NETWORK,
"The request timed out. Please try again.",
error,
"TIMEOUT",
);
}
// For any other unknown errors
return createError(
ErrorType.UNKNOWN,
"An unexpected error occurred.",
error,
"UNKNOWN_ERROR",
);
}
Handles network errors and converts them to the application error format.