Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Making an Global Error Handler with type safety in Typescript

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading