作为一般的软件概念,一些异步操作可以采用三种不同的“路径”:
- 操作成功,我们继续执行
- 操作失败,系统抛出异常
- 该操作由系统(超时)或用户交互取消
在C#中,我们可以处理这3个不同的“路径”,如下所示:
try
{
await myService.doAsync();
}
catch(TaskCanceledException ex)
{
// Here, we know that somehow the Task was cancelled. Whether that is caused by something like
// a timeout or a user explicitly performed some operation to cancel the Task
// This might be apart of some actual business logic and so I want to handle it differently than
// a general exception
}
catch(Exception ex)
{
// This means something went wrong in the downstream code and I probably
// want to log an error and do something else or 'throw' again so upstream
// execution can handle the failure as well
}
但是,尝试在JavaScript或TypeScript中执行此操作并不像我看到的那样优雅,因为我们没有能力检查类型,这意味着我们也无法像我们可以在C#中级联catch
块:
try
{
await myService.doAsync();
}
catch(e)
{
if(e instanceof TaskCancelledError) {
// Here, we know that somehow the Task was cancelled. Whether that is caused by something like
// a timeout or a user explicitly performed some operation to cancel the Task
// This might be apart of some actual business logic and so I want to handle it differently than
// a general exception
}else{
// This means something went wrong in the downstream code and I probably
// want to log an error and do something else or 'throw' again so upstream
// execution can handle the failure as well
}
}
class TaskCancelledError extends Error {
constructor() {
super("The task was cancelled");
}
}
我在上面阐述的是实现TypeScript(JavaScript)和C#之间功能平等的唯一方法吗?我可以做到这一点,但它只是感觉有点hacky.
作为一个旁注,是否可以更改TypeScript来支持这种catch
块的结构,但TS将编译成我们上面看到的代码?