Home > Enterprise >  Making an Global Error Handler with type safety in Typescript
Making an Global Error Handler with type safety in Typescript

Time:01-28

I want to move all error handling into 1 global function to avoid multiple try catch at every place I know we can catch errors with just appending to the await func().catch() but a global solution should also work which is :

async function errorhandler(func) {
 try{
   const result = await func();
   return [result, null];
 }catch (err) {
   console.log(err);
   return [null, err];
 }
}

And using it like:

function mainFunction(){
  const url = "https://jsonplaceholder.typicode.com/todos/"
  const [data, error] = errorhandler(fetch(url));
  if(error) //do something
  data. //no intellisense of methods ?
}

mainFunction()

When I do this I am losing all the intellisense. I have also tried applying some types like this:

async function errorhandler(func: () => Promise<T>): any {
 try{
  const result = await func();
  return [result, null];
 }catch (err) {
  console.log(err);
  return [null, err];
 }
}

function mainFunction(){
  const url = "https://jsonplaceholder.typicode.com/todos/"
  const [data, error]: any = errorhandler(() => fetch(url));
  if(error) //do something
  data. //no intellisense
}

mainFunction()

But didn't work. Any help would be highly appreciated.

I am expecting to get the autocomplete for all the methods that will available for the data field with type safety.

CodePudding user response:

There are a lot of issues with your second attempt.

  • The function has no generic parameters, yet you are trying to use T

  • The return type is just any

  • The function is async, but you are not awaiting the result

  • You also annotated the resulting tuple with any

My suggestion, after fixing these issues, would be to type the return type of errorHandler as a discriminated union of [null, unknown] | [T, null] which can be narrowed by checking the value of data for truthiness.

async function errorhandler<T>(
  func: () => Promise<T>
): Promise<[null, unknown] | [T, null]> {
  try {
    const result = await func();
    return [result, null];
  } catch (err) {
    console.log(err);
    return [null, err];
  }
}

async function mainFunction() {
  const url = "https://jsonplaceholder.typicode.com/todos/";
  const [data, error] = await errorhandler(() => fetch(url));
  if (!data) {
    data;
    // ^? const data: null

    error;
    // ^? const error: unknown
  } else {
    data;
    // ^? const data: Response

    error;
    // ^? const error: null
  }
}

Playground

  • Related