javascript - Javascript ES5/ES6 类和错误处理
问题描述
说我有这样的课
class SomeUIComponentDataStore {
async function getUser() {
try { //do something that can fail}
catch(e) {
// gracefully fail, setting portion of ui to fail state
Sentry.captureException(e); // report to some metrics service
}
}
}
我为每个异步函数重复该模式。失败时我会响应错误,然后将其报告给某个服务(在这种情况下,该服务是 Sentry)。
无论如何我可以创建一个 BaseClass,它会自动用 Sentry.caputreException() 装饰我的 catch 语句。还是每次看到错误时我都必须手动编写它。
解决方案
您可以定义一个装饰器来重用该逻辑并装饰可以抛出的方法:
function catchError(target, name, descriptor) {
const original = descriptor.value;
if (typeof original === 'function') {
descriptor.value = function(...args) {
try {
return original.apply(this, args);
} catch (e) {
Sentry.captureException(e); // report to some metrics service
}
}
}
}
function catchErrorAsync(target, name, descriptor) {
const original = descriptor.value;
if (typeof original === 'function') {
descriptor.value = async function(...args) {
try {
return await original.apply(this, args);
} catch (e) {
Sentry.captureException(e); // report to some metrics service
}
}
}
}
class SomeUIComponentDataStore {
@catchErrorAsync
async getUser() {
//do something that can fail
}
@catchError
otherMethod() {
//do something that can fail
}
}
推荐阅读
- python-3.x - 如何在 Python 中使用 enumerate 为内部循环指定起始索引?
- azure-iot-edge - 具有 1 个以上输入的 IoT Edge 模块失败。在一个模块中使用“input1”和“input2”测试不成功
- apache-spark - 无法从 Spark-Sql 连接到 Hive
- android - 我无法在我的 Dart 插件中运行单独的测试文件
- docker - 为什么我必须先提取图像才能让 docker rest api 返回一些东西?
- c++ - 从 unordered_multimap 中调用另一个类的函数?
- python - 如何分解 Beautifulsoup 中的 HTML 元素以将它们插入 MySQL 数据库表?
- bash - 如何将循环有价值的循环放在 unix 命令的 json 正文中?
- asynchronous - 单个 JMS 队列上的多个使用者
- python - 当每组有多个值时,将熊猫数据框列从长转换为宽