DEV Community

Discussion on: Better error handling with async/await

Collapse
 
mbursill profile image
mbursill

Great solution! I've adapted it for TypeScript and added a defaultError so the error isn't falsy when not provided.

export const handle = <T>(
  promise: Promise<T>,
  defaultError: any = 'rejected'
): Promise<T[] | [T, any]> => {
  return promise
    .then((data) => [data, undefined])
    .catch((error) => Promise.resolve([undefined, error || defaultError]));
};
Enter fullscreen mode Exit fullscreen mode
Collapse
 
daveappz profile image
David

thanks!! you rock