[英]Javascript ES5/ES6 classes and error handling
说我有一堂这样的课
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
}
}
您可以使用Sentry.captureException(e);
创建一个基类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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.