Skip to content

Commit

Permalink
ensure all Data.Error arguments are preserved in .toJSON (#3349)
Browse files Browse the repository at this point in the history
  • Loading branch information
tim-smart authored Jul 25, 2024
1 parent 1ba640c commit c8c71bd
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/nasty-queens-pull.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"effect": patch
---

ensure all Data.Error arguments are preserved in .toJSON
5 changes: 5 additions & 0 deletions packages/effect/src/Data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -530,13 +530,18 @@ export const Error: new<A extends Record<string, any> = {}>(
args: Types.Equals<A, {}> extends true ? void
: { readonly [P in keyof A]: A[P] }
) => Cause.YieldableError & Readonly<A> = (function() {
const plainArgsSymbol = Symbol.for("effect/Data/Error/plainArgs")
return class Base extends core.YieldableError {
constructor(args: any) {
super(args?.message, args?.cause ? { cause: args.cause } : undefined)
if (args) {
Object.assign(this, args)
Object.defineProperty(this, plainArgsSymbol, { value: args, enumerable: false })
}
}
toJSON() {
return { ...(this as any)[plainArgsSymbol], ...this }
}
} as any
})()

Expand Down
19 changes: 19 additions & 0 deletions packages/effect/test/Data.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -279,5 +279,24 @@ describe("Data", () => {
expect(e.message).toStrictEqual("Oh no!")
expect(e.a).toStrictEqual(1)
})

it("toJSON includes all args", () => {
class MyError extends Data.Error<{ message: string; a: number; cause: string }> {}
const e = new MyError({ message: "Oh no!", a: 1, cause: "Boom" })
assert.deepStrictEqual(e.toJSON(), { message: "Oh no!", a: 1, cause: "Boom" })
})
})

describe("TaggedError", () => {
it("toJSON includes all args", () => {
class MyError extends Data.TaggedError("MyError")<{ message: string; a: number; cause: string }> {}
const e = new MyError({ message: "Oh no!", a: 1, cause: "Boom" })
assert.deepStrictEqual(e.toJSON(), {
_tag: "MyError",
message: "Oh no!",
a: 1,
cause: "Boom"
})
})
})
})

0 comments on commit c8c71bd

Please sign in to comment.