What is the preferred way of putting and if condition in a try catch block?

Viewed 52

I have a toast manager try catch block and it works as I expect it

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');
}

It seems to me this maybe inefficent but i don't know if I should remove the try catch or the if condition

1 Answers

I would go for 2 changes here:

  1. use switch instead of if else. easier to read and maintain.
  2. Remove the try catch block. The only exceptions this block could catch could be raised by the showSuccessToast, showWarningToast, and showErrorToast of the toastr. I suppose toastr is a service provided by the ng-bootstrap. If you don't trust such a third-party service you would need to catch errors in many places. Instead, I would consider avoiding polluting the code with the try catch by handling such exceptions at some global level.
Related