Improve error handling for hooks

This commit is contained in:
Luis Alvarez
2020-10-22 15:57:33 -05:00
parent e4a99601f5
commit 3644d637dd
4 changed files with 74 additions and 7 deletions

View File

@@ -4,6 +4,7 @@ import {
CommerceProvider as CoreCommerceProvider,
useCommerce as useCoreCommerce,
} from 'lib/commerce'
import { FetcherError } from '@lib/commerce/utils/errors'
async function getText(res: Response) {
try {
@@ -16,9 +17,9 @@ async function getText(res: Response) {
async function getError(res: Response) {
if (res.headers.get('Content-Type')?.includes('application/json')) {
const data = await res.json()
return data.errors[0]
return new FetcherError({ errors: data.errors, status: res.status })
}
return { message: await getText(res) }
return new FetcherError({ message: await getText(res), status: res.status })
}
export const bigcommerceConfig: CommerceConfig = {

View File

@@ -1,5 +1,6 @@
import { useCallback } from 'react'
import { HookFetcher } from '@lib/commerce/utils/types'
import { CommerceError } from '@lib/commerce/utils/errors'
import type { HookFetcher } from '@lib/commerce/utils/types'
import useCommerceSignup from '@lib/commerce/use-signup'
import type { SignupBody } from './api/customers/signup'
@@ -16,9 +17,10 @@ export const fetcher: HookFetcher<null, SignupBody> = (
fetch
) => {
if (!(firstName && lastName && email && password)) {
throw new Error(
'A first name, last name, email and password are required to signup'
)
throw new CommerceError({
message:
'A first name, last name, email and password are required to signup',
})
}
return fetch({

View File

@@ -0,0 +1,40 @@
export type ErrorData = {
message: string
code?: string
}
export type ErrorProps = {
code?: string
} & (
| { message: string; errors?: never }
| { message?: never; errors: ErrorData[] }
)
export class CommerceError extends Error {
code?: string
errors: ErrorData[]
constructor({ message, code, errors }: ErrorProps) {
const error: ErrorData = message
? { message, ...(code ? { code } : {}) }
: errors![0]
super(error.message)
this.errors = message ? [error] : errors!
if (error.code) this.code = error.code
}
}
export class FetcherError extends CommerceError {
status: number
constructor(
options: {
status: number
} & ErrorProps
) {
super(options)
this.status = options.status
}
}