champ-chatbot / client /services /httpError.tsx
qyle's picture
Deploy from GitLab f5f501ef
8077280
Raw History Blame Contribute Delete
949 Bytes
import type { TranslationKey } from "@/translations";
// A response that isn't ok. Anything else fetch throws is a network error.
export class HttpError extends Error {
status: number;
constructor(status: number) {
super(`HTTP ${status}`);
this.name = "HttpError";
this.status = status;
}
}
type AuthErrorKey = Extract<TranslationKey, "error_signed_out" | "error_email_not_verified">;
// Said instead of any request's own failure message: the user has to act before anything works.
export const authErrorKey = (status?: number): AuthErrorKey | undefined => {
if (status === 401) return "error_signed_out";
if (status === 403) return "error_email_not_verified";
return undefined;
};
export const requestErrorKey = <K extends TranslationKey>(
err: unknown,
serverKey: K,
networkKey: K,
): K | AuthErrorKey => {
if (!(err instanceof HttpError)) return networkKey;
return authErrorKey(err.status) ?? serverKey;
};