Javascript: Difference between explicitly throwing an error object and not - javascript

In javascript, I have noticed two ways of throwing an error:
1)
throw "An error";
2)
throw new Error('An object error')
Is there any advantage of choosing one way over the other?
Is one considered a better practice?
Thanks

Basically, JavaScript is implicitly throwing an Error object with "An error" as the message when you use method one. Unless you need to throw a different kind of exception (for example, one that has different properties explaining the error) method one is fine.
However, if you plan on throwing more complex exceptions in the future, you'll need to use method 2, as you'll need to define which object you're throwing.
Basically, for this purpose both are equivalent. I'd go with method 2, since it will put you in the right mindset down the road ;)

An Error object has nice little extras like error.name and (in Firefox) error.stack.
If you need those, do throw an error explicitly. However, most people merely use the error.toString() method (often called implicitly). In the latter case it's overkill to create an Error object in the first place, so throwing a string works just as well.

Related

Keep JS from creating exception objects

So i have situation where I have to save the solution from a giant formula (calculation) to a variable and i know for sure that this will often have no solution so
I will use a try catch clause. And I can not calculate it twice because it would be, among possible other things, much too long (timewise).
But from what I know, with every catch, an exception object (etc) will get created. Is it possible to keep this from happening (some command or similar)?
Because I know for sure I will never need these because I know why it is impossible sometimes, but this automatic behavior would obviously cause unnecessary stack and processor (and that way runTIME) -usage.
Or is this default behavior not the case for js?
But from what I know, with every catch, an exception object (etc) will get created...
That's incorrect. An Error object will only be created if an error is thrown, not just because you have a catch block in your code. (And technically, in JavaScript, you can throw other things, they don't have to be Error instances, though when the browser or JavaScript engine throws something, it's always an Error object [directly or indirectly via a subclass].) If an error is created and thrown, and your code doesn't keep it, it'll immediately be eligible for garbage collection anyway. Creating and garbage collecting a single object is not a significant effort.

AggregateError - Javascript

I recently noticed the new AggregateError object (ECMAScript 2021). Is there any cases or best practices where it is recommended to use it?
Description from the MDN wiki:
The AggregateError object represents an error when several errors need to be wrapped in a single error. It is thrown when multiple errors need to be reported by an operation, for example by Promise.any(), when all promises passed to it reject.
So, use it whenever the description fits - if you want to throw multiple errors at once.

Is it a good practice to throw exceptions on errors when parsing internal language?

I'm working on a JS library, as a part of it, I built a parser for small sort of a markup language to enable users to use more complicated expressions. I wanted to know if it is a good practice to throw an exception if there is an error in internal expression syntax and let users use the function within the try/catch block, or if it's better for example to return false and inform the user that there was a parsing error some other way (possibly console)? I can't really tell if throwing an exceptions is common practice when building a library, I know that jQuery for example throws some errors in its source, but jQuery is huge framework-like library so I would expect that, but is it common for small size libraries?
The problem with throwing exceptions on parse errors is that once you throw an exception, it is very difficult to resume the parse. That means that the parser intends to give up as soon as it hits the first syntax error; in other words, that it expects the user to fix one error at a time.
It's possible that you currently don't do any error recovery, so this might not bother you. But it should.
Are you certain that you're not going to want to try error recovery, particularly after listening to your users grumbling about how they have to try the parse dozens or hundreds of times to find all of their errors? And when you do eventually start to implement error recovery, will you be happy about having to find and change every place where the parser in order to change the way it is called?

What exactly does dirty-chai.js do?

The package description for dirty-chai is a bit opaque for a newbie:
Function form for terminating assertion properties
What is an 'assertion property' in this context and what does terminating mean? Why are they not normally "terminated"? I have so many questions. An example without dirty-chai and and an example with, that shows the benefit would be great.
I think one of the key reasons for dirty-chai is that it is not considered good practice to make assertions on property access (at least for some in the JavaScript community).
Without the plug-in chai allows you write tests like this:
chai.expect(someFunctionThatReturnsTrue(args)).to.be.true
If the test failed, that means someFunctionThatReturnsTrue(args) must have been returning something other than true and from that you know to start debugging its code to see why.
However, for this test to function, accessing the true property needs to make assertions and disrupt the code execution if the assertion fails (for example, by throwing an Exception).
Linters generally do not know how property access is done and would by default assume that the accessing of a property will not have any side-effects (i.e. alter the environment), especially not things like throwing exceptions (or cause other control-flow disrupting consequences).
Therefore, if you write something.true (without parentheses), the linter will assume that you simply want to access a property of something named true. If the expression goes nowhere (not used in an assignment, as function parameters, or in other evaluations), the linter would flag this a a potential typo or something else. Therefore, the previous valid case in chai will generate a linter error.
And these kind of linter errors can be useful in some cases because JavaScript does not complain if you try to access properties that do not exist. For example, what if you do have a typo in your test code?
chai.expect(someFunctionThatReturnsTrue(args)).to.be.ture
// ~~~~ not `true`, obviously a typo
This test would pass no matter what someFunctionThatReturnsTrue(args) returns. Because accessing .ture simply returns undefined and will not throw an error. Then you may miss some coding errors in someFunctionThatReturnsTrue() if you are forced to ignore these linter errors by chai.
Worse, if there is any error, you may assume that it's not in someFunctionThatReturnsTrue() because that test (wrongly) passes.
Thus the plugin, dirty-chai, by converting assertions by property access (like .true) into calling these properties as function (.true()) make sure linters will know that these statements can change the control flow:
chai.expect(someFunctionThatReturnsTrue(args)).to.be.true()
// Linter now knows you are expecting something to happen during `.true()` call
// and won't complain anymore
And now if you make a typo, the test will fail (by throwing an exception)
chai.expect(someFunctionThatReturnsTrue(args)).to.be.ture()
// ~~~~ Will throw something like
// `...to.be.ture is not a function`

What type of exception should be thrown in JavaScript?

What type of object should be thrown in JavaScript?
I see a lot of examples which throw a plain old string and there seems to be a semi-standard Error type. Should I prefer one over the other?
The Error object and specific error objects such as TypeError are fully standardized in the ECMAScript specification. There are, however, common non-standard properties of these objects available in most browsers.
You can throw whatever you like, so long as your error handling code knows what to do with the objects you throw, but there are advantages to using Error objects:
Consistency with handling errors thrown by native code, such as having a message property, so you don't have to write different code to handle native errors and your own errors;
Error objects in Mozilla and other browsers have very useful non-standard properties, such as fileName, lineNumber and stack. You only get these on Error objects and they can be very useful for debugging.

Categories

Resources