Skip to content

Commit

Permalink
fix: BaseError@walk to return null when predicate fn not matches (#…
Browse files Browse the repository at this point in the history
…874)

* fix: `BaseError@walk` to return `null` when predicate fn not matches

* Update young-spiders-taste.md

---------

Co-authored-by: jxom <[email protected]>
  • Loading branch information
Alexsey and jxom authored Jul 11, 2023
1 parent 072daaa commit a9bc9f6
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/young-spiders-taste.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"viem": patch
---

Fixed `BaseError.walk` to return `null` if the predicate callback is not satisfied.
10 changes: 10 additions & 0 deletions src/errors/base.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,3 +153,13 @@ test('walk: predicate fn', () => {
Version: [email protected]]
`)
})

test('walk: predicate fn (no match)', () => {
class FooError extends BaseError {}
class BarError extends BaseError {}

const err = new BaseError('test1', {
cause: new Error('test2', { cause: new BarError('test3') }),
})
expect(err.walk((err) => err instanceof FooError)).toBeNull()
})
5 changes: 3 additions & 2 deletions src/errors/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ export class BaseError extends Error {

function walk(err: unknown, fn?: (err: unknown) => boolean): unknown {
if (fn?.(err)) return err
if ((err as Error).cause) return walk((err as Error).cause, fn)
return err
if (err && typeof err === 'object' && 'cause' in err)
return walk(err.cause, fn)
return fn ? null : err
}

1 comment on commit a9bc9f6

@vercel
Copy link

@vercel vercel bot commented on a9bc9f6 Jul 11, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.