From 6bc223adb3c995027c3f8d70af9d6eeb6ca57742 Mon Sep 17 00:00:00 2001 From: Catalin Pinte Date: Mon, 28 Nov 2022 08:17:43 +0200 Subject: [PATCH] Improve error handling (#886) * Improve error handling * Update fetch-graphql-api.ts --- packages/commerce/src/api/utils/errors.ts | 4 +++- .../saleor/src/api/utils/fetch-graphql-api.ts | 15 ++++++++++----- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/packages/commerce/src/api/utils/errors.ts b/packages/commerce/src/api/utils/errors.ts index 5d54f8a75..227090c14 100644 --- a/packages/commerce/src/api/utils/errors.ts +++ b/packages/commerce/src/api/utils/errors.ts @@ -42,7 +42,9 @@ export class CommerceNetworkError extends Error { } export const normalizeZodIssues = (issues: ZodError['issues']) => - issues.map(({ path, message }) => `${message} at "${path.join('.')}" field`) + issues.map(({ path, message }) => + path.length ? `${message} at "${path.join('.')}" field` : message + ) export const getOperationError = (operation: string, error: unknown) => { if (error instanceof ZodError) { diff --git a/packages/saleor/src/api/utils/fetch-graphql-api.ts b/packages/saleor/src/api/utils/fetch-graphql-api.ts index 313b57a05..45f5326d5 100644 --- a/packages/saleor/src/api/utils/fetch-graphql-api.ts +++ b/packages/saleor/src/api/utils/fetch-graphql-api.ts @@ -2,7 +2,6 @@ import type { GraphQLFetcher } from '@vercel/commerce/api' import { API_URL } from '../../const' import { getError } from '../../utils/handle-fetch-response' -import { getCommerceApi } from '..' import { getToken } from '../../utils/index' const fetchGraphqlApi: GraphQLFetcher = async ( @@ -10,7 +9,6 @@ const fetchGraphqlApi: GraphQLFetcher = async ( { variables } = {}, headers?: HeadersInit ) => { - const config = getCommerceApi().getConfig() const token = getToken() const res = await fetch(API_URL!, { @@ -28,10 +26,17 @@ const fetchGraphqlApi: GraphQLFetcher = async ( }), }) - const { data, errors, status } = await res.json() + const { data, errors, message, type, status } = await res.json() - if (errors) { - throw getError(errors, status) + if (errors || res.status >= 400) { + throw getError( + errors || [ + { + message: `${type ? `${type}, ` : ''}${message}`, + }, + ], + status || res.status + ) } return { data, res }