Skip to content

Commit 8bce0f1

Browse files
author
Basarat Ali Syed
committed
wrap
1 parent e3709c1 commit 8bce0f1

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

docs/types/exceptions.md

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,8 +57,24 @@ catch(e) {
5757
console.log(e);
5858
}
5959
```
60-
*Don't do that*. Such raw strings result in a very painful debugging and error handling experience.
60+
*Don't do that*. The fundamental benefit of `Error` objects is that they automatically keep track of where they were built and originated as the `stack` property.
6161

62+
Raw strings result in a very painful debugging experience and complicate error analysis from logs.
63+
64+
## You don't have to `throw` an error
65+
It is okay to pass an `Error` object around. This is conventional in NodeJS callback style code which take callbacks with the first argument as an error object.
66+
67+
```js
68+
function myFunction (callback: (e?: Error)) {
69+
doSomethingAsync(function () {
70+
if (somethingWrong) {
71+
callback(new Error('This is my error'))
72+
} else {
73+
callback();
74+
}
75+
});
76+
}
77+
```
6278

6379
## Exceptional cases
6480
`Exceptions should be exceptional` is a common saying in computer science. There are few resons why this is true for JavaScript (and TypeScript) as well.
@@ -127,4 +143,6 @@ function validate(value: number): {error?: string} {
127143
if (value < 0 || value > 100) return {error:'Invalid value'};
128144
}
129145
```
130-
And not its represented in the type system.
146+
And now its represented in the type system.
147+
148+
> Unless you want to handle the error in a very generic (simple / catch-all etc) way, don't *throw* an error.

0 commit comments

Comments
 (0)