thinknimble / tn-models-fp

TS version of tn-models
2 stars 0 forks source link

Auto handling of specific error types #202

Open oudeismetis opened 2 weeks ago

oudeismetis commented 2 weeks ago

It would be great if you could set up a Collection Manager or an API and configure it with a callback for any and all calls that result in...say...a 401 error.

The main use case being when a user's token expires or gets deleted. There are certain critical API endpoints that should never fail for the user. If they do, then it likely means the users token is bad. In the callback I could then maybe call an endpoint to verify that their token is in fact bad and then, based on the result of that call, either redirect them to their dashboard or to the login page.

In my app currently, a 401 results in a broken page with nothing making it obvious that the user needs to log out and log back in. To fix that I'll have to go through all of my business logic, find every call to every critical API service and handle each one of those individually. Will then need to remember to do that for any new calls that are added to the business logic in the future.

paribaker commented 2 weeks ago

I like the idea of allowing custom callbacks in general, but I think the use case that you are referring to should get handled by the project. In our react side projects all 401 errors are handled using a generic 401 handler. I also have an open PR in the bs to add one for the vue side.

paribaker commented 2 weeks ago

Here is a sample:

axiosInstance.interceptors.response.use(
  (config) => config,
  (err: unknown) => {
    if (isAxiosError(err)) {
      logAxiosError(err)
      if (err.status === 401 || err.response?.status === 401) {
        const { clearAuth } = useAuth.getState().actions
        clearAuth()
        window.location.replace('/')
      }
    }
  },
)

The logic here does not redirect the user through the router but I think that can easily be changed!

lakardion commented 2 weeks ago

This sounds like something that the axios client owns as Pari commented, it involves the interceptor.
So to my view this escapes the responsibility of the library considering the axios client is a parameter the user passes in