Send error as json to client? #6205
-
|
see the output below - import { Console, Data, Effect, pipe, Schema } from "effect"
// json serialization
class UnluckError extends Data.TaggedError("UnluckError")<{
readonly rolled: number
}> {}
Effect.runPromise(
pipe(
Effect.sync(() => Math.random()),
Effect.flatMap((rolled) =>
rolled > 0.5
? Effect.succeed(123)
: Effect.fail(new UnluckError({ rolled })),
),
Effect.either,
Effect.map(
Schema.encodeSync(
Schema.Either({
left: Schema.instanceOf(UnluckError),
right: Schema.Number,
}),
),
),
Effect.tap(Console.log),
Effect.tapError(Console.error),
),
)
/*
{
_tag: "Left",
left: UnluckError: An error has occurred
at <anonymous> ...1.test.ts:22:27),
}
*/I found out this works... But Jesus Christ why would i do so much typing and do not follow DRY? I swear it can be simplified somehow... // left: Schema.instanceOf(UnluckError),
// ✔️
left: Schema.Struct({
_tag: Schema.String,
rolled: Schema.Number.pipe(),
}), |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
The issue is Fix: use import { Console, Effect, pipe, Schema } from "effect";
// Define the error WITH a schema (not just Data.TaggedError)
class UnluckError extends Schema.TaggedError<UnluckError>()("UnluckError", {
rolled: Schema.Number,
}) {}
Effect.runPromise(
pipe(
Effect.sync(() => Math.random()),
Effect.flatMap((rolled) =>
rolled > 0.5
? Effect.succeed(123)
: Effect.fail(new UnluckError({ rolled })),
),
Effect.either,
Effect.map(
Schema.encodeSync(
Schema.Either({
left: UnluckError, // use the class directly — it IS a schema
right: Schema.Number,
}),
),
),
Effect.tap(Console.log),
Effect.runSync,
),
);Output: Why
Alternatively, keep const UnluckErrorSchema = Schema.Struct({
_tag: Schema.Literal("UnluckError"),
rolled: Schema.Number,
});
// Use UnluckErrorSchema in your Either — transform the class to plain object manuallyBut |
Beta Was this translation helpful? Give feedback.
The issue is
Schema.instanceOf(UnluckError)—instanceOfchecks the class instance but doesn't know how to encode it as a plain object. It passes the class instance through as-is, which serializes to{}(class instances have non-enumerable prototype methods).Fix: use
Schema.TaggedErrorinstead ofData.TaggedError+instanceOf: