diff --git a/{{cookiecutter.project_slug}}/clients/web/react/src/utils/server-errors.ts b/{{cookiecutter.project_slug}}/clients/web/react/src/utils/server-errors.ts new file mode 100644 index 000000000..d88b6056f --- /dev/null +++ b/{{cookiecutter.project_slug}}/clients/web/react/src/utils/server-errors.ts @@ -0,0 +1,23 @@ +import { isAxiosError, AxiosError } from 'axios' + +export function handleDRFAPIErrorsOrReThrow(error: AxiosError | Error): string[]{ + if (isAxiosError(error)){ + const e: AxiosError = error + + const { data } = (e as AxiosError)?.response ?? null + if (data) { + const isArrayOfStrings = + Array.isArray(data) && data.length && typeof data[0] === 'string' + const isObjectOfErrors = Object.keys(data).every((key) => Array.isArray(data[key])) + return (isArrayOfStrings + ? data + : isObjectOfErrors + ? Object.keys(data).map((key) => data[key]) + : ['Something went wrong']) as string[] + + } + return [] + } + throw error as Error +} +