说我有一堂这样的课
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语句。还是我每次看到错误都必须手动编写它。
答案 0 :(得分:1)
您可以定义一个装饰器以重用该逻辑并装饰可能抛出的方法:
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
}
}
答案 1 :(得分:0)
您可以使用Sentry.captureException(e);
创建基类,然后为自定义try / catch功能提供可重写的功能。
class BaseClass {
function onGetUser() {
throw new Error("Method not implemented");
}
function onGetUserFail() {
throw new Error("Method not implemented");
}
async function getUser() {
try {
onGetUser();
} catch (e) {
onGetUserFail();
Sentry.captureException(e);
}
}
}
class SomeUIComponentDataStore extends BaseClass {
function onGetUser() {
// do something
}
function onGetUserFail() {
// do something
}
}