axiosreact-queryreact-error-boundary

error prop's type of fallbackRender in react-error-boundary question


i want to use AxiosError like below.

    <ErrorBoundary
      onReset={reset}
      fallbackRender={({ resetErrorBoundary, error }) => {
        // here! type error!
        if(error.response.data.statusCode === 403) {
          return (<div>Need Login</div>)
        }

        return (
          <div>
            There was an error!
            <button onClick={() => resetErrorBoundary()}>재시도</button>
          </div>
        )
      }}
    >
      <Suspense fallback={<Loading />}>
        <Profile />
      </Suspense>
    </ErrorBoundary>

but error default type is Error. how to change from Error type to AxiosError type?


Solution

  • axios exposes a util to check if something is an axios error, which also performs type narrowing. So a simple:

    if (axios.isAxiosError(error) && error.response.data.statusCode === 403) {
      
    }
    

    should suffice.

    Note that ErrorBoundaries are triggered with different kinds of errors, e.g., if you app fails to render for some other reason. If that's the case, the error won't be an AxiosError, but a normal Error. That is why defensive runtime checking is generally a good idea. It's also the reason why catch(error) now defaults the type to unknown in TypeScript, and why react-query also gives you unknown per default for errors.