Javascript 在试捕块中放置和如果条件的首选方式是什么?

Javascript 在试捕块中放置和如果条件的首选方式是什么?,javascript,try-catch,ng-bootstrap,Javascript,Try Catch,Ng Bootstrap,我有一个吐司经理尝试抓块,它的工作,因为我期待它 showToast(status: string, message: string) { try { if (status === 'success') { this.toastr.showSuccessToast(message) } else if (status === 'warning'){ this.toastr.showWarningToast(message) } else { this.

我有一个吐司经理尝试抓块,它的工作,因为我期待它

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条件

  • 使用
    开关
    而不是
    if-else
    。易于阅读和维护
  • 删除
    try catch
    块。此块可以捕获的唯一异常可以由
    toastr
    showSuccessToast
    showWarningToast
    showerroToast
    引发。我想
    toastr
    是ng引导程序提供的服务。如果你不信任这样的第三方服务,你需要在很多地方发现错误。相反,我会考虑避免使用“代码”污染代码。
    您是否希望这些函数中的任何一个抛出错误?为什么你认为代码效率很低?不确定它到底出了什么问题。为什么你认为这是错误的?我在想这应该是组织以外的尝试捕获。。像一个函数里面试试…你为什么这么认为?(不是说这是错的,只是好奇而已)