Shi*_*il 6 javascript typescript
如何在 typeScript 中抛出包含错误详细信息的对象的新错误?
我正在使用 jest 来测试打字稿代码,我想抛出新的错误,如下所示:
mock.spyOn(AppUtils,'util_plane').mockImplementation(() => {
throw new Error("Error Message",{status:403})
})
Run Code Online (Sandbox Code Playgroud)
当我这样做时,编译器抱怨说:
Expected 0-1 arguments, but got 2.ts(2554)
Ale*_* L. 11
错误构造函数不希望{status: number}被传递给它。您可以创建并使用自定义错误类:
class CustomError extends Error {
status: number;
constructor(message: string, { status }: { status: number }) {
super(message);
this.status = status
}
}
// ...
throw new CustomError('Error Message', { status: 403 })
Run Code Online (Sandbox Code Playgroud)
或者您可以在创建后将状态属性分配给错误:
throw Object.assign(new Error('Error Message'), { status: 403 })
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4885 次 |
| 最近记录: |