重写捕获错误的高阶函数以捕获异步错误? [英] Rewrite error catching higher order function to catch async errors?

查看:85
本文介绍了重写捕获错误的高阶函数以捕获异步错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里,我有一个功能很好,可以捕获同步错误,并在重新抛出错误之前对其进行处理.

Here I have a function that works well for catching sync errors, and doing something with them before re-throwing them.

    function logExceptions<T extends (...args: any[]) => any>(func: T): (...funcArgs: Parameters<T>) => ReturnType<T> {
      return (...args: Parameters<T>): ReturnType<T> => {
        try {
          return func(...args);
        } catch (err) {
          console.log(func.name + " caused an error")
          throw err;
        }
      };
    }

function syncExample() { 
  throw new Error()
}

logExceptions(syncExample)();

console.log

console.log

"syncExample导致错误"

"syncExample caused an error"

我可以重写此功能以使其成为不可知论者,并且还可以用于异步功能吗?

Can I rewrite this function to become async agnostic and also work for async functions?

async function asyncExample() { 
  throw new Error()
}
logExceptions(asyncExample)();

所需的console.log

desired console.log

"asyncExample导致错误"

"asyncExample caused an error"

实际console.log

actual console.log

"

推荐答案

我可以重写此功能以使其成为不可知论者,并且还可以用于异步功能吗?

Can I rewrite this function to become async agnostic and also work for async functions?

不.虽然您可以尝试重载它并检测该函数是否返回诺言,但这是非常脆弱的.最好编写一个单独的函数来包装异步函数:

No. While you could try to overload it and detect whether the function would return a promise or not, that's very fragile. Better write a separate function for wrapping asynchronous functions:

function logExceptions<T extends any[], U>(func: (...args: T) => PromiseLike<U>): (...args: T) => Promise<U> {
  return async (...args) => {
    try {
      return await func(...args);
    } catch (err) {
      console.log(func.name + " caused an error")
      throw err;
    }
  };
}

这篇关于重写捕获错误的高阶函数以捕获异步错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆