← full-stack-fastapi-template / frontend/src/utils.ts
| 1 | import { AxiosError } from "axios" |
| 2 | import type { ApiError } from "./client" |
| 3 | |
| 4 | function extractErrorMessage(err: ApiError): string { |
| 5 | if (err instanceof AxiosError) { |
| 6 | return err.message |
| 7 | } |
| 8 | |
| 9 | const errDetail = (err.body as any)?.detail |
| 10 | if (Array.isArray(errDetail) && errDetail.length > 0) { |
| 11 | return errDetail[0].msg |
| 12 | } |
| 13 | return errDetail || "Something went wrong." |
| 14 | } |
| 15 | |
| 16 | export const handleError = function ( |
| 17 | this: (msg: string) => void, |
| 18 | err: ApiError, |
| 19 | ) { |
| 20 | const errorMessage = extractErrorMessage(err) |
| 21 | this(errorMessage) |
| 22 | } |
| 23 | |
| 24 | export const getInitials = (name: string): string => { |
| 25 | return name |
| 26 | .split(" ") |
| 27 | .slice(0, 2) |
| 28 | .map((word) => word[0]) |
| 29 | .join("") |
| 30 | .toUpperCase() |
| 31 | } |
| 32 |