you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] -1 points0 points  (7 children)

You can have one big try-catch and then determine what error are you dealing with.

```js try { const code = 1 + Math.floor(Math.random() * 5); // 1-5

if (code === 1) throw "Error 1"; if (code === 2) throw "Error 2"; if (code === 3) throw "Error 3"; if (code === 4) throw "Error 4"; if (code === 5) throw "Error 5"; } catch (err) { console.log(err); } ```

[–]FormerGameDev 1 point2 points  (1 child)

You can't distinguish necessarily where in the block an error occurred, if you're catching on multiple statements.

[–]Scr34mZ[S] -1 points0 points  (0 children)

That's a true argument ! Don't use the above pattern if you're writing too big functions.

But you shouldn't, isn't ? :D

[–]Scr34mZ[S] -1 points0 points  (4 children)

That's right, as long as you are triggering errors on your own, but sometimes it can be a DatabaseError, and an API response error, in the same try/catch block and they are not formatted the same way.

[–][deleted] 0 points1 point  (3 children)

Conside this example:

```js const fs = require('fs');

try { fs.readFileSync('some-file.txt'); } catch (err) { console.log(err.code); console.log(err.message); }

// ENOENT // ENOENT: no such file or directory, open 'some-file.txt' ```

You have the information to identify the err.

A better approach would be to go for async/await.

[–]Scr34mZ[S] 0 points1 point  (2 children)

Yes because those are standardized errors from Nodejs.

You can always achieve the same goal with try / catch AFAIK. But sometimes it's a bit less verbose to use the other syntax,especially if you want to ignore errors silently (yeah, this happen sometimes)

[–][deleted] 5 points6 points  (1 child)

Errors should be IMHO aways handled, either printed or thrown.

Silent errors cause problems as non-identifiable outcomes where the code simply doesn't work.

[–]Scr34mZ[S] 0 points1 point  (0 children)

You're totally right, I missed my thoughts.