我在这里提出的建议不是使用类,而是使用会创建所需错误结构的函数。所以我们不会丢失原始错误中的任何信息,但我们也可以添加一些元数据来表示特殊类型的错误。考虑
// 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);
}