在 try catch 块中放置 if 条件的首选方法是什么?
What is the preferred way of putting and if condition in a try catch block?
我有一个 toast 管理器 try catch 块,它按我预期的方式工作
showToast(status: string, message: string) {
try {
if (status === 'success') {
this.toastr.showSuccessToast(message)
}
else if (status === 'warning'){
this.toastr.showWarningToast(message)
}
else {
this.toastr.showErrorToast(message)
}
} catch {
console.log('Toast failed');
}
在我看来这可能是低效的,但我不知道是否应该删除 try catch 或 if 条件
我会在这里进行 2 处更改:
- 使用
switch
而不是 if else
。更易于阅读和维护。
- 删除
try catch
块。 toastr
的 showSuccessToast
、showWarningToast
和 showErrorToast
可以引发此块唯一可以捕获的异常。我想 toastr
是由 ng-bootstrap 提供的服务。如果您不信任此类第三方服务,则需要在许多地方捕获错误。相反,我会考虑避免使用 handling such exceptions at some global level. 污染代码。
我有一个 toast 管理器 try catch 块,它按我预期的方式工作
showToast(status: string, message: string) {
try {
if (status === 'success') {
this.toastr.showSuccessToast(message)
}
else if (status === 'warning'){
this.toastr.showWarningToast(message)
}
else {
this.toastr.showErrorToast(message)
}
} catch {
console.log('Toast failed');
}
在我看来这可能是低效的,但我不知道是否应该删除 try catch 或 if 条件
我会在这里进行 2 处更改:
- 使用
switch
而不是if else
。更易于阅读和维护。 - 删除
try catch
块。toastr
的showSuccessToast
、showWarningToast
和showErrorToast
可以引发此块唯一可以捕获的异常。我想toastr
是由 ng-bootstrap 提供的服务。如果您不信任此类第三方服务,则需要在许多地方捕获错误。相反,我会考虑避免使用 handling such exceptions at some global level. 污染代码。