There is no bigger context but for me it is a mistake to do both. If you have a mistake and can check it then do it right there. Do not use try-catch
unless it is necessary.
Launch a Error
almost always an error. Throwing some class you inherit from it may be useful in some cases.
The first code you’re casting a Error
if you already know that there is an error, this is because this variable already indicates this, some mechanism that used gives you a result that indicates this. This error creates a complex error object that is understood by catch
, therefore the object e
will receive precisely this object that contains a lot of information, among them the message you used to create object, so when you print this object it shows this message and some other relevant information that this object has. This object gains information about the execution situation at that time. There is other information that is not shown by default. If you want to know more about this object read to documentation (note that the implementation may have nothing but the message).
The second code throws an error but does not create a complex object, it generates only one string, then when that object is received in e
in the catch
is this object that is printed, so only the message without anything additional.
The second I would say is more wrong because it does nothing interesting, is the same as doing:
//...ações
if (error) console.log('Falha temporária do servidor');
The first even has some utility because it collects information about the execution that can be used, but so it is better:
//...ações
if (error) console.log(new Error('Falha temporária do servidor'));
I put in the Github for future reference.
Do not use exceptions for flow control, especially to divert a flow that does not need to be diverted. Read more in Why should we avoid returning error codes?, I speak even of this pattern used here.
yes, the second will be returned in catch a string and in the first will be returned the Error object, which has the property
.message
,.fileName
,.lineNumber
,.columnNumber
and.stack
and you can still customize by informing a different file or line:new Error([message[, fileName[, lineNumber]]])
– Guilherme Nascimento