user1637281
user1637281

Reputation:

When to use throw or log errors?

I have a function that wraps console.log like this.

NS.log("error");

which I use for error logging. It is a simple one liner to let the app developer know that something went wrong. It does not stop program flow and shows up unobtrusively in the console.

However, I've heard in university courses, etc., that using a try/throw/catch is best practice as it uses an error control system already in place.

However, I don't need the error to "bubble" up after a throw statement. I would catch it immediately like this:

try {
    throw "error"
} catch (e) {
}

Are there any cons to simply logging the error as opposed to using a more formal structure.

My assumption is that try/throw/catch is for more complex structures.

But I wanted to make sure.

Notes:

Upvotes: 0

Views: 2161

Answers (2)

Ryan
Ryan

Reputation: 5682

If it works for you and those your working with then it works; and there is no need to change.

Technically try/throw/catch is best practice, and in most languages that's what you should use.

In javascript however, I can tell you that try/throw/catch has pretty bad performance. Also a lot of errors in javascript are of a dynamic nature. The should be dealt with yes. But a lot of them won't break your application.

So why would you want them to bubble up and annoy your users?

TL:DR I'm not discouraging the use of try/throw/catch sometimes you should use it, as @JohnSaunders said. But the fact that often in javascript errors don't break anything and you often take a performance hit using try/throw/catch, means you should think about the cost/benefit ratio of this 'best practice' before mindlessly implementing it.

Upvotes: 1

grepit
grepit

Reputation: 22392

I am happy you are considering your options and thinking through the process. However

  1. The try statement lets you to test a block of code for errors.
  2. The catch statement lets you handle the error.
  3. The throw statement lets you create custom errors.

so in your case if you have some kind of log process in place then use try catch. example

try {

} catch (e) {
   NS.log(err);
}

more information /source

Upvotes: 1

Related Questions