Skip to content

Commit 72e0a7c

Browse files
committed
Add custom message to _unsafeUnwrap*
1 parent ac52282 commit 72e0a7c

File tree

6 files changed

+1148
-1056
lines changed

6 files changed

+1148
-1056
lines changed

.changeset/hip-cycles-clean.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'neverthrow': minor
3+
---
4+
5+
Add custom message to \_unsafeUnwrap

README.md

+9-1
Original file line numberDiff line numberDiff line change
@@ -1571,9 +1571,17 @@ _unsafeUnwrapErr({
15711571
15721572
// ^ Now the error object will have a `.stack` property containing the current stack
15731573
```
1574+
You can also conditionally add a custom error message that will be propagated with the error object. By default this error message will be `Called '_unsafeUnwrap' on an Err` when called on an `Err` and `Called '_unsafeUnwrapErr' on an Ok` when called on an `Ok`.
15741575

1575-
---
1576+
```typescript
1577+
_unsafeUnwrapErr({
1578+
message: 'Your custom error message',
1579+
withStackTrace: true,
1580+
})
1581+
```
15761582

1583+
---
1584+
15771585
If you find this package useful, please consider [sponsoring me](https://github.com/sponsors/supermacro/) or simply [buying me a coffee](https://ko-fi.com/gdelgado)!
15781586

15791587
---

package-lock.json

+2-2
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/_internals/error.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import { Result } from '../result'
22

33
export interface ErrorConfig {
4-
withStackTrace: boolean
4+
withStackTrace?: boolean
5+
message?: string
56
}
67

78
const defaultErrorConfig: ErrorConfig = {

src/result.ts

+6-2
Original file line numberDiff line numberDiff line change
@@ -379,7 +379,11 @@ export class Ok<T, E> implements IResult<T, E> {
379379
}
380380

381381
_unsafeUnwrapErr(config?: ErrorConfig): E {
382-
throw createNeverThrowError('Called `_unsafeUnwrapErr` on an Ok', this, config)
382+
throw createNeverThrowError(
383+
config?.message ?? 'Called `_unsafeUnwrapErr` on an Ok',
384+
this,
385+
config,
386+
)
383387
}
384388
}
385389

@@ -461,7 +465,7 @@ export class Err<T, E> implements IResult<T, E> {
461465
}
462466

463467
_unsafeUnwrap(config?: ErrorConfig): T {
464-
throw createNeverThrowError('Called `_unsafeUnwrap` on an Err', this, config)
468+
throw createNeverThrowError(config?.message ?? 'Called `_unsafeUnwrap` on an Err', this, config)
465469
}
466470

467471
_unsafeUnwrapErr(_?: ErrorConfig): E {

0 commit comments

Comments
 (0)