我应该如何以正确的方式抛出异常,以免丢失任何信息?
考虑以下示例:
try {
this.stripe.customers.create({ ... });
} catch(e) {
throw new MyCustomCreateCustomersException();
}
在这种情况下,我可以在日志中看到MyCustomCreateCustomersException
被抛出以及在何处被抛出。但是该堆栈跟踪不包含任何与引发Stripe有关的内容,因此这里丢失了真正的错误。
自从我遗漏e
并没有使用它以来,我认为这很明显,但是我不确定使用它的最佳方法是什么?我也希望有自定义的异常,这似乎是一个好习惯,但是我不想更深入地丢失任何信息。
MyCustomCreateCustomersException
是从Error
继承的。
答案 0 :(得分:0)
我在这里提出的建议是使用类函数来创建所需的错误结构,而不是使用类。因此,我们不会从原始错误中丢失任何信息,但是我们还可以添加一些元数据来表示特殊类型的错误。考虑
// we are copying orginal error to not loose the data:
const createCustomerError = (e: Error) => ({...e, errorType: 'CREATE_CUSTOMER'});
const otherError = (e: Error) => ({...e, errorType: 'OTHER'});
感谢您拥有堆栈跟踪,消息以及其他信息。您可以随时添加所需的元数据。很好的方法是对以下类型的错误进行建模:
type ErrorType = 'CREATE_CUSTOMER' | 'OTHER' // can be also enum
type MyError = {errorType: ErrorType } & Error;
// also we should define our error function output as MyError:
const createCustomerError = (e: Error): MyError => ({...e, errorType: 'CREATE_CUSTOMER'});
const otherError = (e: Error): MyError => ({...e, errorType: 'OTHER'});
由于这种类型,您可以使用标准的switch / if处理程序来处理特定的错误,例如:
// some parent handler which will handle those re thrown errors
switch(error.errorType) {
case 'CREATE_CUSTOMER':
someHandler();
break;
case 'OTHER':
someHandler2();
break;
default:
defaultErrrorHandler();
}
最后但并非最不重要。使用函数错误构造函数看起来像:
try {
this.stripe.customers.create({ ... });
} catch(e) {
throw createCustomerError(e);
}