Best practice logging Apollo errors: within custom React hook or when the hook is used?

Viewed 15

I am working with a custom React hook which uses the @apollo/client library to call a GraphQL API.

import {useMutation} from '@apollo/client';

export const useCreateAccount() => {
   ...
   const {loading, error, data} =  useMutation(query, options);
   ...
   return [loading ,data, error];
}

And in my component, I am calling my custom hook:

import {useCreateAccount} from './createAccountHook.js';

export const MyComponent() => {
   ...
   const [loading ,data, error] = useCreateAccount();
   ...
}

I also have a logging library for logging errors. I want to log GraphQL errors that fail because may a parameter is unaccepted, or an account with the same name exists. I can't change the API so I need to do some logging from the React UI side.

Wondering if best practice is to log errors in my custom React hook or within the React component that calls the custom React hook? Below are two ideas I thought of but open to what makes the most sense when it comes to logging more-or-less server-sided errors.


Option A

export const useCreateAccount() => {
  ...
  const {loading, error, data} =  useMutation(query, options);
  logger.error('An error occurred', error);
  ...
  return [loading ,data, error];
}

Option B

import {useCreateAccount} from './createAccountHook.js';

export const MyComponent() => {
   ...
   const [data, loading, error] = useCreateAccount();
   if (error) { logger.error('an error occurred', error};
  ...
}
1 Answers

Between the two options presented I'd suggest the implementation that requires less work/effort on the consumers.

In this case Option A is the superior choice as it abstracts away the error logging from the consumer. Any component can use the custom useCreateAccount hook and aren't concerned with any additional logging of the data requests it is making. This makes Option A a more DRY solution as well.

With Option B devs and consuming components would need to handle the (likely) duplicated logic of if (error) { logger.error('an error occurred', error};. This is more overhead to account for and you get possibly inconsistent error logging if the dev that day doesn't apply the same logging logic and messaging.

Related