diff --git a/.specs/AI_ERROR_DOMAIN_MODEL.md b/.specs/AI_ERROR_DOMAIN_MODEL.md index a576bb981e..1d2236c8ea 100644 --- a/.specs/AI_ERROR_DOMAIN_MODEL.md +++ b/.specs/AI_ERROR_DOMAIN_MODEL.md @@ -1,7 +1,5 @@ # AI Error Domain Model -**Status: DRAFT** - ## Overview Replace the current `AiError` design with a comprehensive, provider-agnostic domain model for errors originating from large language model providers. The new design uses the `reason` pattern (see `Effect.catchReason`) where `AiError` is a top-level wrapper error containing `module`, `method`, and a `reason` field that holds the semantic error. diff --git a/.specs/README.md b/.specs/README.md index 8a6c152dc3..27f6726dee 100644 --- a/.specs/README.md +++ b/.specs/README.md @@ -8,3 +8,4 @@ This directory contains specifications for all major features and enhancements i - [cli-prompt-autocomplete.md](cli-prompt-autocomplete.md) - Add a typed filter auto-complete prompt for CLI selects. - [worker-error-reason-pattern.md](worker-error-reason-pattern.md) - Refactor WorkerError to use the reason pattern with structured reasons. - [http-client-error-reason-pattern.md](http-client-error-reason-pattern.md) - Refactor HttpClientError to a reason-based wrapper with per-reason classes. +- [http-server-error-reason-pattern.md](http-server-error-reason-pattern.md) - Refactor HttpServerError to use the reason pattern with per-reason classes. diff --git a/.specs/cli-with-fallback-prompt.md b/.specs/cli-with-fallback-prompt.md index 0b97c41c62..60b75c0c71 100644 --- a/.specs/cli-with-fallback-prompt.md +++ b/.specs/cli-with-fallback-prompt.md @@ -1,5 +1,3 @@ -**Status: DRAFT** - ## Overview Port `withFallbackPrompt` from effect 3 into the new CLI API. The feature adds diff --git a/.specs/http-client-error-reason-pattern.md b/.specs/http-client-error-reason-pattern.md index 506e3a8f9f..b8f82779bf 100644 --- a/.specs/http-client-error-reason-pattern.md +++ b/.specs/http-client-error-reason-pattern.md @@ -1,7 +1,5 @@ # HttpClientError Reason Pattern -**Status: DRAFT** - ## Overview Refactor `HttpClientError` to follow the reason pattern used by `SocketError` and `AiError`. The new design introduces per-reason error classes and a top-level `HttpClientError` wrapper with a `reason` field. This provides ergonomic error handling with `Effect.catchReason`, while preserving rich request/response context. diff --git a/.specs/http-server-error-reason-pattern.md b/.specs/http-server-error-reason-pattern.md new file mode 100644 index 0000000000..222e76c6ab --- /dev/null +++ b/.specs/http-server-error-reason-pattern.md @@ -0,0 +1,151 @@ +# HttpServerError Reason Pattern + +## Overview + +Refactor `HttpServerError` to use the reason pattern (see `HttpClientError` and +`SocketError`). `HttpServerError` becomes a thin wrapper around a `reason` union +of semantic reason classes. The existing reason tags and response mappings stay +the same while enabling `Effect.catchReason` flows. + +## Goals + +- Replace the string `reason` union with per-reason classes. +- Introduce a top-level `HttpServerError` wrapper containing a `reason` field. +- Preserve existing reason tags (`RequestParseError`, `RouteNotFound`, + `InternalError`, `ResponseError`). +- Keep the current message formatting and response status mapping. +- Update call sites to construct the wrapper with reason instances. +- Keep `isHttpServerError` aligned with the wrapper only. +- Keep `ServeError` behavior separate from `HttpServerError`. + +## Non-Goals + +- Changing response status behavior or routing semantics. +- Adding new error categories or altering error messages. +- Refactoring unrelated HTTP server modules. + +## Current State + +`HttpServerError` is a type alias of `RequestError | ResponseError`, implemented +as `Data.TaggedError` classes that store a literal `reason` field. Call sites +instantiate `new RequestError({ reason: "RouteNotFound", ... })` or +`new ResponseError({ ... })` directly, and `Respondable` handling is implemented +on these classes. + +## Proposed Design + +### Reason Classes + +Introduce reason classes using `Data.TaggedError` with the existing tags: + +- `RequestParseError` +- `RouteNotFound` +- `InternalError` +- `ResponseError` + +Shared fields (all reasons): + +- `request: HttpServerRequest.HttpServerRequest` +- `description?: string` +- `cause?: unknown` + +Response-specific fields: + +- `response: HttpServerResponse.HttpServerResponse` + +Each reason implements `Respondable.Respondable` and defines +`[Respondable.TypeId]` with the same status mapping as today: + +- `RequestParseError` -> 400 +- `RouteNotFound` -> 404 +- `InternalError` -> 500 +- `ResponseError` -> 500 + +### Message Formatting + +Reason classes preserve the existing message strings: + +- Request reasons: ` ( )`, with `: ` when set. +- `ResponseError`: ` ( )`, with `: ` when set. + +### Reason Union Types + +- `RequestError` becomes a type alias for request reasons. +- `HttpServerErrorReason` is the union of all reason classes. + +### HttpServerError Wrapper + +Add a `HttpServerError` wrapper class: + +```ts +export class HttpServerError extends Data.TaggedError("HttpServerError")<{ + readonly reason: HttpServerErrorReason +}> { + readonly [TypeId] = TypeId + + override get message(): string { + return this.reason.message + } +} +``` + +Behavior: + +- Copies `reason.cause` onto the wrapper when present (SocketError-style). +- Implements `Respondable.Respondable`, delegating `[Respondable.TypeId]` to the reason. +- Optional convenience getters for `request` and `response` delegate to the reason. +- `isHttpServerError` guards only the wrapper. +- Preserve the existing `stack` format (`${this.name}: ${this.message}`) on the wrapper. + +### ServeError Guarding + +`ServeError` continues to represent server startup failures, but +`isHttpServerError` must not match it. Implement this by tightening the guard to +check the wrapper `_tag` or by moving `ServeError` onto its own type id. + +### Construction Pattern + +```ts +Effect.fail( + new HttpServerError({ + reason: new RouteNotFound({ request }) + }) +) +``` + +Handling: + +```ts +Effect.catchReason("HttpServerError", "RouteNotFound", (reason) => Effect.logWarning(reason.message)) +``` + +## Impacted Areas + +- `packages/effect/src/unstable/http/HttpServerError.ts` +- `packages/effect/src/unstable/http/HttpRouter.ts` +- `packages/effect/src/unstable/http/HttpEffect.ts` +- `packages/effect/src/unstable/http/HttpServerRequest.ts` +- `packages/effect/src/unstable/http/HttpMiddleware.ts` +- `packages/platform-node/src/NodeHttpServer.ts` +- `packages/platform-node/src/NodeClusterHttp.ts` +- `packages/platform-bun/src/BunHttpServer.ts` +- `packages/platform-bun/src/BunClusterHttp.ts` +- `packages/effect/src/unstable/eventlog/EventLogServer.ts` + +## Test Plan + +- Add tests for reason message formatting and status mapping. +- Verify wrapper delegates `message`, `request`, and `response`. +- Verify `isHttpServerError` only matches the wrapper. +- Verify `ServeError` is excluded from `isHttpServerError`. +- Validate `Respondable` delegation (wrapper -> reason). + +Follow the `it.effect` pattern and existing Effect test conventions. + +## Validation + +- `pnpm lint-fix` +- `pnpm test ` +- `pnpm check` (run `pnpm clean` if check fails) +- `pnpm build` +- `pnpm docgen` diff --git a/.specs/worker-error-reason-pattern.md b/.specs/worker-error-reason-pattern.md index 91bbc6aa83..0edafb6708 100644 --- a/.specs/worker-error-reason-pattern.md +++ b/.specs/worker-error-reason-pattern.md @@ -1,5 +1,3 @@ -**Status: DRAFT** - ## Overview Refactor `WorkerError` to follow the new `reason` pattern (see `SocketError` and diff --git a/packages/effect/src/FileSystem.ts b/packages/effect/src/FileSystem.ts index 8812f546c1..f4c2e225e0 100644 --- a/packages/effect/src/FileSystem.ts +++ b/packages/effect/src/FileSystem.ts @@ -41,8 +41,7 @@ import * as Cause from "./Cause.ts" import * as Effect from "./Effect.ts" import { pipe } from "./Function.ts" import * as Layer from "./Layer.ts" -import type { PlatformError } from "./PlatformError.ts" -import { BadArgument, SystemError } from "./PlatformError.ts" +import { badArgument, type PlatformError, systemError } from "./PlatformError.ts" import type * as Pull from "./Pull.ts" import type { Scope } from "./Scope.ts" import * as ServiceMap from "./ServiceMap.ts" @@ -732,14 +731,18 @@ export const make = ( pipe( impl.access(path), Effect.as(true), - Effect.catchTag("PlatformError", (e) => e.reason === "NotFound" ? Effect.succeed(false) : Effect.fail(e)) + Effect.catchTag( + "PlatformError", + (e) => + e.reason._tag === "SystemError" && e.reason.kind === "NotFound" ? Effect.succeed(false) : Effect.fail(e) + ) ), readFileString: (path, encoding) => Effect.flatMap(impl.readFile(path), (_) => Effect.try({ try: () => new TextDecoder(encoding).decode(_), catch: (cause) => - new BadArgument({ + badArgument({ module: "FileSystem", method: "readFileString", description: "invalid encoding", @@ -784,7 +787,7 @@ export const make = ( Effect.try({ try: () => new TextEncoder().encode(data), catch: (cause) => - new BadArgument({ + badArgument({ module: "FileSystem", method: "writeFileString", description: "could not encode string", @@ -796,10 +799,10 @@ export const make = ( }) const notFound = (method: string, path: string) => - new SystemError({ + systemError({ module: "FileSystem", method, - reason: "NotFound", + kind: "NotFound", description: "No such file or directory", pathOrDescriptor: path }) @@ -825,10 +828,10 @@ const notFound = (method: string, path: string) => * return Effect.succeed("{\"test\": true}") * } * return Effect.fail( - * new PlatformError.SystemError({ + * PlatformError.systemError({ * module: "FileSystem", * method: "readFileString", - * reason: "NotFound", + * kind: "NotFound", * description: "File not found", * pathOrDescriptor: path * }) diff --git a/packages/effect/src/PlatformError.ts b/packages/effect/src/PlatformError.ts index d8df669e71..4bdebd6f96 100644 --- a/packages/effect/src/PlatformError.ts +++ b/packages/effect/src/PlatformError.ts @@ -9,22 +9,12 @@ const TypeId = "~effect/platform/PlatformError" * @since 4.0.0 * @category Models */ -export class BadArgument extends Data.TaggedError("PlatformError")<{ +export class BadArgument extends Data.TaggedError("BadArgument")<{ module: string method: string description?: string | undefined cause?: unknown }> { - /** - * @since 4.0.0 - */ - readonly [TypeId]: typeof TypeId = TypeId - - /** - * @since 4.0.0 - */ - readonly reason = "BadArgument" as const - /** * @since 4.0.0 */ @@ -37,7 +27,7 @@ export class BadArgument extends Data.TaggedError("PlatformError")<{ * @since 4.0.0 * @category Model */ -export type SystemErrorReason = +export type SystemErrorKind = | "AlreadyExists" | "BadResource" | "Busy" @@ -54,8 +44,8 @@ export type SystemErrorReason = * @since 4.0.0 * @category models */ -export class SystemError extends Data.TaggedError("PlatformError")<{ - reason: SystemErrorReason +export class SystemError extends Data.TaggedError("SystemError")<{ + kind: SystemErrorKind module: string method: string description?: string | undefined @@ -63,16 +53,11 @@ export class SystemError extends Data.TaggedError("PlatformError")<{ pathOrDescriptor?: string | number | undefined cause?: unknown }> { - /** - * @since 4.0.0 - */ - readonly [TypeId]: typeof TypeId = TypeId - /** * @since 4.0.0 */ override get message(): string { - return `${this.reason}: ${this.module}.${this.method}${ + return `${this.kind}: ${this.module}.${this.method}${ this.pathOrDescriptor !== undefined ? ` (${this.pathOrDescriptor})` : "" }${this.description ? `: ${this.description}` : ""}` } @@ -82,4 +67,48 @@ export class SystemError extends Data.TaggedError("PlatformError")<{ * @since 4.0.0 * @category Models */ -export type PlatformError = BadArgument | SystemError +export class PlatformError extends Data.TaggedError("PlatformError")<{ + reason: BadArgument | SystemError +}> { + constructor(reason: BadArgument | SystemError) { + if ("cause" in reason) { + super({ reason, cause: reason.cause } as any) + } else { + super({ reason }) + } + } + + /** + * @since 4.0.0 + */ + readonly [TypeId]: typeof TypeId = TypeId + + override get message(): string { + return this.reason.message + } +} + +/** + * @since 4.0.0 + * @category constructors + */ +export const systemError = (options: { + readonly kind: SystemErrorKind + readonly module: string + readonly method: string + readonly description?: string | undefined + readonly syscall?: string | undefined + readonly pathOrDescriptor?: string | number | undefined + readonly cause?: unknown +}): PlatformError => new PlatformError(new SystemError(options)) + +/** + * @since 4.0.0 + * @category constructors + */ +export const badArgument = (options: { + readonly module: string + readonly method: string + readonly description?: string | undefined + readonly cause?: unknown +}): PlatformError => new PlatformError(new BadArgument(options)) diff --git a/packages/effect/src/encoding/Base64.ts b/packages/effect/src/encoding/Base64.ts index ab4cd493b3..fea5fe7310 100644 --- a/packages/effect/src/encoding/Base64.ts +++ b/packages/effect/src/encoding/Base64.ts @@ -85,7 +85,7 @@ export const decode = (str: string): Result.Result => if (length % 4 !== 0) { return Result.fail( new EncodingError({ - reason: "Decode", + kind: "Decode", module: "Base64", input: stripped, message: `Length must be a multiple of 4, but is ${length}` @@ -97,7 +97,7 @@ export const decode = (str: string): Result.Result => if (index !== -1 && ((index < length - 2) || (index === length - 2 && stripped[length - 1] !== "="))) { return Result.fail( new EncodingError({ - reason: "Decode", + kind: "Decode", module: "Base64", input: stripped, message: `Found a '=' character, but it is not at the end` @@ -123,7 +123,7 @@ export const decode = (str: string): Result.Result => } catch (e) { return Result.fail( new EncodingError({ - reason: "Decode", + kind: "Decode", module: "Base64", input: stripped, message: e instanceof Error ? e.message : "Invalid input" diff --git a/packages/effect/src/encoding/Base64Url.ts b/packages/effect/src/encoding/Base64Url.ts index f11e021a01..bf25f81d73 100644 --- a/packages/effect/src/encoding/Base64Url.ts +++ b/packages/effect/src/encoding/Base64Url.ts @@ -52,7 +52,7 @@ export const decode = (str: string): Result.Result => return Result.fail( new EncodingError({ module: "Base64Url", - reason: "Decode", + kind: "Decode", input: stripped, message: `Length should be a multiple of 4, but is ${length}` }) @@ -63,7 +63,7 @@ export const decode = (str: string): Result.Result => return Result.fail( new EncodingError({ module: "Base64Url", - reason: "Decode", + kind: "Decode", input: stripped, message: "Invalid input" }) diff --git a/packages/effect/src/encoding/EncodingError.ts b/packages/effect/src/encoding/EncodingError.ts index 6c4d357df9..48d05609c8 100644 --- a/packages/effect/src/encoding/EncodingError.ts +++ b/packages/effect/src/encoding/EncodingError.ts @@ -17,7 +17,7 @@ export type EncodingErrorTypeId = typeof EncodingErrorTypeId * @since 4.0.0 */ export class EncodingError extends Data.TaggedError("EncodingError")<{ - reason: "Decode" | "Encode" + kind: "Decode" | "Encode" module: string input: unknown message: string diff --git a/packages/effect/src/encoding/Hex.ts b/packages/effect/src/encoding/Hex.ts index ab8069a345..2402ba6e41 100644 --- a/packages/effect/src/encoding/Hex.ts +++ b/packages/effect/src/encoding/Hex.ts @@ -57,7 +57,7 @@ export const decode = (str: string): Result.Result => return Result.fail( new EncodingError({ module: "Hex", - reason: "Decode", + kind: "Decode", input: str, message: `Length must be a multiple of 2, but is ${bytes.length}` }) @@ -78,7 +78,7 @@ export const decode = (str: string): Result.Result => return Result.fail( new EncodingError({ module: "Hex", - reason: "Decode", + kind: "Decode", input: str, message: e instanceof Error ? e.message : "Invalid input" }) diff --git a/packages/effect/src/unstable/cli/Command.ts b/packages/effect/src/unstable/cli/Command.ts index 1995508b1d..16ef203c8f 100644 --- a/packages/effect/src/unstable/cli/Command.ts +++ b/packages/effect/src/unstable/cli/Command.ts @@ -660,7 +660,7 @@ const mapHandler = ( * : FileSystem.layerNoop({ * access: () => * Effect.fail( - * new PlatformError.BadArgument({ + * PlatformError.badArgument({ * module: "FileSystem", * method: "access" * }) diff --git a/packages/effect/src/unstable/encoding/Msgpack.ts b/packages/effect/src/unstable/encoding/Msgpack.ts index af5b60260a..a3b02ac558 100644 --- a/packages/effect/src/unstable/encoding/Msgpack.ts +++ b/packages/effect/src/unstable/encoding/Msgpack.ts @@ -23,7 +23,7 @@ const MsgPackErrorTypeId = "~effect/encoding/MsgPack/MsgPackError" * @category errors */ export class MsgPackError extends Data.TaggedError("MsgPackError")<{ - readonly reason: "Pack" | "Unpack" + readonly kind: "Pack" | "Unpack" readonly cause: unknown }> { /** @@ -35,7 +35,7 @@ export class MsgPackError extends Data.TaggedError("MsgPackError")<{ * @since 4.0.0 */ override get message() { - return this.reason + return this.kind } } @@ -58,7 +58,7 @@ export const encode = (): Channel.Channel< try { return Effect.succeed(Arr.map(chunk, (item) => packr.pack(item) as Uint8Array)) } catch (cause) { - return Effect.fail(new MsgPackError({ reason: "Pack", cause })) + return Effect.fail(new MsgPackError({ kind: "Pack", cause })) } }) }) @@ -120,7 +120,7 @@ export const decode = (): Channel.Channel< out.push(...error.values) } } else { - return Effect.fail(new MsgPackError({ reason: "Unpack", cause })) + return Effect.fail(new MsgPackError({ kind: "Unpack", cause })) } } } diff --git a/packages/effect/src/unstable/encoding/Ndjson.ts b/packages/effect/src/unstable/encoding/Ndjson.ts index 21b02c4009..27c63b3a00 100644 --- a/packages/effect/src/unstable/encoding/Ndjson.ts +++ b/packages/effect/src/unstable/encoding/Ndjson.ts @@ -18,7 +18,7 @@ const encoder = new TextEncoder() * @category errors */ export class NdjsonError extends Data.TaggedError("NdjsonError")<{ - readonly reason: "Pack" | "Unpack" + readonly kind: "Pack" | "Unpack" readonly cause: unknown }> { /** @@ -30,7 +30,7 @@ export class NdjsonError extends Data.TaggedError("NdjsonError")<{ * @since 4.0.0 */ override get message() { - return this.reason + return this.kind } } @@ -51,7 +51,7 @@ export const encodeString = (): Channel.Channel< try { return Effect.succeed(Arr.of(input.map((item) => JSON.stringify(item)).join("\n") + "\n")) } catch (cause) { - return Effect.fail(new NdjsonError({ reason: "Pack", cause })) + return Effect.fail(new NdjsonError({ kind: "Pack", cause })) } })) ) @@ -126,7 +126,7 @@ export const decodeString = (options?: { try { return Effect.succeed(Arr.map(chunk, (line) => JSON.parse(line))) } catch (cause) { - return Effect.fail(new NdjsonError({ reason: "Unpack", cause })) + return Effect.fail(new NdjsonError({ kind: "Unpack", cause })) } }) } diff --git a/packages/effect/src/unstable/http/Cookies.ts b/packages/effect/src/unstable/http/Cookies.ts index 0c623c15f6..90750ccd40 100644 --- a/packages/effect/src/unstable/http/Cookies.ts +++ b/packages/effect/src/unstable/http/Cookies.ts @@ -133,10 +133,30 @@ const CookieErrorTypeId = "~effect/http/Cookies/CookieError" * @since 4.0.0 * @category errors */ -export class CookiesError extends Data.TaggedError("CookieError")<{ - readonly reason: "InvalidName" | "InvalidValue" | "InvalidDomain" | "InvalidPath" | "InfinityMaxAge" +export class CookiesErrorReason extends Data.Error<{ + readonly _tag: + | "InvalidCookieName" + | "InvalidCookieValue" + | "InvalidCookieDomain" + | "InvalidCookiePath" + | "CookieInfinityMaxAge" readonly cause?: unknown +}> {} + +/** + * @since 4.0.0 + * @category errors + */ +export class CookiesError extends Data.TaggedError("CookieError")<{ + readonly reason: CookiesErrorReason }> { + /** + * @since 4.0.0 + */ + static fromReason(reason: CookiesError["reason"]["_tag"], cause?: unknown): CookiesError { + return new CookiesError({ reason: new CookiesErrorReason({ _tag: reason, cause }) }) + } + /** * @since 4.0.0 */ @@ -146,7 +166,7 @@ export class CookiesError extends Data.TaggedError("CookieError")<{ * @since 4.0.0 */ override get message() { - return this.reason + return this.reason._tag } } @@ -382,24 +402,24 @@ export function makeCookie( options?: Cookie["options"] | undefined ): Result.Result { if (!fieldContentRegExp.test(name)) { - return Result.fail(new CookiesError({ reason: "InvalidName" })) + return Result.fail(CookiesError.fromReason("InvalidCookieName")) } const encodedValue = encodeURIComponent(value) if (encodedValue && !fieldContentRegExp.test(encodedValue)) { - return Result.fail(new CookiesError({ reason: "InvalidValue" })) + return Result.fail(CookiesError.fromReason("InvalidCookieValue")) } if (options !== undefined) { if (options.domain !== undefined && !fieldContentRegExp.test(options.domain)) { - return Result.fail(new CookiesError({ reason: "InvalidDomain" })) + return Result.fail(CookiesError.fromReason("InvalidCookieDomain")) } if (options.path !== undefined && !fieldContentRegExp.test(options.path)) { - return Result.fail(new CookiesError({ reason: "InvalidPath" })) + return Result.fail(CookiesError.fromReason("InvalidCookiePath")) } if (options.maxAge !== undefined && !Duration.isFinite(Duration.fromDurationInputUnsafe(options.maxAge))) { - return Result.fail(new CookiesError({ reason: "InfinityMaxAge" })) + return Result.fail(CookiesError.fromReason("CookieInfinityMaxAge")) } } diff --git a/packages/effect/src/unstable/http/HttpEffect.ts b/packages/effect/src/unstable/http/HttpEffect.ts index 5a7ac12e4a..1af9e5c869 100644 --- a/packages/effect/src/unstable/http/HttpEffect.ts +++ b/packages/effect/src/unstable/http/HttpEffect.ts @@ -14,8 +14,7 @@ import * as Stream from "../../Stream.ts" import * as UndefinedOr from "../../UndefinedOr.ts" import * as HttpBody from "./HttpBody.ts" import { type HttpMiddleware, tracer } from "./HttpMiddleware.ts" -import { causeResponse, clientAbortFiberId, RequestError } from "./HttpServerError.ts" -import type { HttpServerError } from "./HttpServerError.ts" +import { causeResponse, clientAbortFiberId, HttpServerError, InternalError } from "./HttpServerError.ts" import { HttpServerRequest } from "./HttpServerRequest.ts" import * as Request from "./HttpServerRequest.ts" import type { HttpServerResponse } from "./HttpServerResponse.ts" @@ -362,17 +361,18 @@ export const fromWebHandler = ( services: fiber.services }) if (requestResult._tag === "Failure") { - return resume(Effect.fail(requestResult.failure)) + return resume(Effect.fail(new HttpServerError({ reason: requestResult.failure }))) } handler(requestResult.success).then( (response) => resume(Effect.succeed(Response.fromWeb(response))), (cause) => resume(Effect.fail( - new RequestError({ - cause, - request, - reason: "InternalError", - description: "HttpApp.fromWebHandler: Error in handler" + new HttpServerError({ + reason: new InternalError({ + cause, + request, + description: "HttpApp.fromWebHandler: Error in handler" + }) }) )) ) diff --git a/packages/effect/src/unstable/http/HttpRouter.ts b/packages/effect/src/unstable/http/HttpRouter.ts index 6a94b2cb22..69fd122896 100644 --- a/packages/effect/src/unstable/http/HttpRouter.ts +++ b/packages/effect/src/unstable/http/HttpRouter.ts @@ -170,7 +170,11 @@ export const make = Effect.gen(function*() { result = router.find("GET", request.url) } if (result === undefined) { - return Effect.fail(new HttpServerError.RequestError({ reason: "RouteNotFound", request })) + return Effect.fail( + new HttpServerError.HttpServerError({ + reason: new HttpServerError.RouteNotFound({ request }) + }) + ) } const route = result.handler if (route.prefix !== undefined) { diff --git a/packages/effect/src/unstable/http/HttpServerError.ts b/packages/effect/src/unstable/http/HttpServerError.ts index c16e3b6f1c..b8f7f10f7c 100644 --- a/packages/effect/src/unstable/http/HttpServerError.ts +++ b/packages/effect/src/unstable/http/HttpServerError.ts @@ -16,18 +16,22 @@ const TypeId = "~effect/http/HttpServerError" * @since 4.0.0 * @category error */ -export type HttpServerError = RequestError | ResponseError - -/** - * @since 4.0.0 - * @category error - */ -export class RequestError extends Data.TaggedError("HttpServerError")<{ - readonly reason: "RequestParseError" | "RouteNotFound" | "InternalError" - readonly request: Request.HttpServerRequest - readonly description?: string - readonly cause?: unknown +export class HttpServerError extends Data.TaggedError("HttpServerError")<{ + readonly reason: HttpServerErrorReason }> implements Respondable.Respondable { + constructor(props: { + readonly reason: HttpServerErrorReason + }) { + if ("cause" in props.reason) { + super({ + ...props, + cause: props.reason.cause + } as any) + } else { + super(props) + } + } + /** * @since 4.0.0 */ @@ -36,21 +40,48 @@ export class RequestError extends Data.TaggedError("HttpServerError")<{ /** * @since 4.0.0 */ - override stack = `${this.name}: ${this.message}`; + override stack = `${this.name}: ${this.message}` + + /** + * @since 4.0.0 + */ + get request(): Request.HttpServerRequest { + return this.reason.request + } + + /** + * @since 4.0.0 + */ + get response(): Response.HttpServerResponse | undefined { + return "response" in this.reason ? this.reason.response : undefined + } /** * @since 4.0.0 */ [Respondable.TypeId]() { - return Effect.succeed( - Response.empty({ - status: this.reason === "InternalError" - ? 500 - : this.reason === "RouteNotFound" - ? 404 - : 400 - }) - ) + return this.reason[Respondable.TypeId]() + } + + override get message(): string { + return this.reason.message + } +} + +/** + * @since 4.0.0 + * @category error + */ +export class RequestParseError extends Data.TaggedError("RequestParseError")<{ + readonly request: Request.HttpServerRequest + readonly description?: string + readonly cause?: unknown +}> implements Respondable.Respondable { + /** + * @since 4.0.0 + */ + [Respondable.TypeId]() { + return Effect.succeed(Response.empty({ status: 400 })) } get methodAndUrl() { @@ -58,8 +89,57 @@ export class RequestError extends Data.TaggedError("HttpServerError")<{ } override get message() { - const prefix = `${this.reason} (${this.methodAndUrl})` - return this.description ? `${prefix}: ${this.description}` : prefix + return formatRequestMessage(this._tag, this.description, this.methodAndUrl) + } +} + +/** + * @since 4.0.0 + * @category error + */ +export class RouteNotFound extends Data.TaggedError("RouteNotFound")<{ + readonly request: Request.HttpServerRequest + readonly description?: string + readonly cause?: unknown +}> implements Respondable.Respondable { + /** + * @since 4.0.0 + */ + [Respondable.TypeId]() { + return Effect.succeed(Response.empty({ status: 404 })) + } + + get methodAndUrl() { + return `${this.request.method} ${this.request.url}` + } + + override get message() { + return formatRequestMessage(this._tag, this.description, this.methodAndUrl) + } +} + +/** + * @since 4.0.0 + * @category error + */ +export class InternalError extends Data.TaggedError("InternalError")<{ + readonly request: Request.HttpServerRequest + readonly description?: string + readonly cause?: unknown +}> implements Respondable.Respondable { + /** + * @since 4.0.0 + */ + [Respondable.TypeId]() { + return Effect.succeed(Response.empty({ status: 500 })) + } + + get methodAndUrl() { + return `${this.request.method} ${this.request.url}` + } + + override get message() { + return formatRequestMessage(this._tag, this.description, this.methodAndUrl) } } @@ -73,26 +153,12 @@ export const isHttpServerError = (u: unknown): u is HttpServerError => hasProper * @since 4.0.0 * @category error */ -export class ResponseError extends Data.TaggedError("HttpServerError")<{ +export class ResponseError extends Data.TaggedError("ResponseError")<{ readonly request: Request.HttpServerRequest readonly response: Response.HttpServerResponse readonly description?: string readonly cause?: unknown }> implements Respondable.Respondable { - /** - * @since 4.0.0 - */ - readonly [TypeId] = TypeId - /** - * @since 4.0.0 - */ - readonly reason = "ResponseError" as const - - /** - * @since 4.0.0 - */ - override stack = `${this.name}: ${this.message}`; - /** * @since 4.0.0 */ @@ -105,22 +171,34 @@ export class ResponseError extends Data.TaggedError("HttpServerError")<{ } override get message() { - const info = `${this.reason} (${this.response.status} ${this.methodAndUrl})` + const info = `${this._tag} (${this.response.status} ${this.methodAndUrl})` return this.description ? `${info}: ${this.description}` : info } } +/** + * @since 4.0.0 + * @category error + */ +export type RequestError = RequestParseError | RouteNotFound | InternalError + +/** + * @since 4.0.0 + * @category error + */ +export type HttpServerErrorReason = RequestError | ResponseError + /** * @since 4.0.0 * @category error */ export class ServeError extends Data.TaggedError("ServeError")<{ readonly cause: unknown -}> { - /** - * @since 4.0.0 - */ - readonly [TypeId] = TypeId +}> {} + +const formatRequestMessage = (reason: string, description: string | undefined, info: string) => { + const prefix = `${reason} (${info})` + return description ? `${prefix}: ${description}` : prefix } /** diff --git a/packages/effect/src/unstable/http/HttpServerRequest.ts b/packages/effect/src/unstable/http/HttpServerRequest.ts index dcdd0d3aa3..fbd368ebad 100644 --- a/packages/effect/src/unstable/http/HttpServerRequest.ts +++ b/packages/effect/src/unstable/http/HttpServerRequest.ts @@ -19,7 +19,7 @@ import * as Cookies from "./Cookies.ts" import * as Headers from "./Headers.ts" import * as HttpIncomingMessage from "./HttpIncomingMessage.ts" import { hasBody, type HttpMethod } from "./HttpMethod.ts" -import { type HttpServerError, RequestError } from "./HttpServerError.ts" +import { HttpServerError, type RequestError, RequestParseError } from "./HttpServerError.ts" import * as Multipart from "./Multipart.ts" import * as UrlParams from "./UrlParams.ts" @@ -261,10 +261,11 @@ export const schemaBodyFormJson = ( if (isMultipart(request)) { return Effect.flatMap( Effect.mapError(request.multipart, (cause) => - new RequestError({ - request, - reason: "RequestParseError", - cause + new HttpServerError({ + reason: new RequestParseError({ + request, + cause + }) })), parseMultipart(field) ) @@ -360,17 +361,19 @@ class ServerRequestImpl extends Inspectable.Class implements HttpServerRequest { ? Stream.fromReadableStream({ evaluate: () => this.source.body as any, onError: (cause) => - new RequestError({ - request: this, - reason: "RequestParseError", - cause + new HttpServerError({ + reason: new RequestParseError({ + request: this, + cause + }) }) }) : Stream.fail( - new RequestError({ - request: this, - reason: "RequestParseError", - description: "can not create stream from empty body" + new HttpServerError({ + reason: new RequestParseError({ + request: this, + description: "can not create stream from empty body" + }) }) ) } @@ -384,10 +387,11 @@ class ServerRequestImpl extends Inspectable.Class implements HttpServerRequest { Effect.tryPromise({ try: () => this.source.text(), catch: (cause) => - new RequestError({ - request: this, - reason: "RequestParseError", - cause + new HttpServerError({ + reason: new RequestParseError({ + request: this, + cause + }) }) }) )) @@ -399,10 +403,11 @@ class ServerRequestImpl extends Inspectable.Class implements HttpServerRequest { Effect.try({ try: () => JSON.parse(text) as unknown, catch: (cause) => - new RequestError({ - request: this, - reason: "RequestParseError", - cause + new HttpServerError({ + reason: new RequestParseError({ + request: this, + cause + }) }) })) } @@ -412,10 +417,11 @@ class ServerRequestImpl extends Inspectable.Class implements HttpServerRequest { Effect.try({ try: () => UrlParams.fromInput(new URLSearchParams(_)), catch: (cause) => - new RequestError({ - request: this, - reason: "RequestParseError", - cause + new HttpServerError({ + reason: new RequestParseError({ + request: this, + cause + }) }) })) } @@ -443,7 +449,7 @@ class ServerRequestImpl extends Inspectable.Class implements HttpServerRequest { get multipartStream(): Stream.Stream { return Stream.pipeThroughChannel( - Stream.mapError(this.stream, (cause) => new Multipart.MultipartError({ reason: "InternalError", cause })), + Stream.mapError(this.stream, (cause) => Multipart.MultipartError.fromReason("InternalError", cause)), Multipart.makeChannel(this.headers) ) } @@ -457,10 +463,11 @@ class ServerRequestImpl extends Inspectable.Class implements HttpServerRequest { Effect.tryPromise({ try: () => this.source.arrayBuffer(), catch: (cause) => - new RequestError({ - request: this, - reason: "RequestParseError", - cause + new HttpServerError({ + reason: new RequestParseError({ + request: this, + cause + }) }) }) )) @@ -469,10 +476,11 @@ class ServerRequestImpl extends Inspectable.Class implements HttpServerRequest { get upgrade(): Effect.Effect { return Effect.fail( - new RequestError({ - request: this, - reason: "RequestParseError", - description: "Not an upgradeable ServerRequest" + new HttpServerError({ + reason: new RequestParseError({ + request: this, + description: "Not an upgradeable ServerRequest" + }) }) ) } @@ -506,9 +514,8 @@ export const toWebResult = (self: HttpServerRequest, options?: { const url = toURL(self) if (url === undefined) { return Result.fail( - new RequestError({ + new RequestParseError({ request: self, - reason: "RequestParseError", description: "Invalid URL" }) ) diff --git a/packages/effect/src/unstable/http/Multipart.ts b/packages/effect/src/unstable/http/Multipart.ts index 0a5e172fef..1e4cc0121c 100644 --- a/packages/effect/src/unstable/http/Multipart.ts +++ b/packages/effect/src/unstable/http/Multipart.ts @@ -4,6 +4,7 @@ import * as Arr from "../../Array.ts" import * as Cause from "../../Cause.ts" import * as Channel from "../../Channel.ts" +import * as Data from "../../Data.ts" import * as Effect from "../../Effect.ts" import * as Exit from "../../Exit.ts" import * as FileSystem from "../../FileSystem.ts" @@ -123,11 +124,25 @@ const MultipartErrorTypeId = "~effect/http/Multipart/MultipartError" * @since 4.0.0 * @category Errors */ -export class MultipartError extends Schema.ErrorClass(MultipartErrorTypeId)({ - _tag: Schema.tag("MultipartError"), - reason: Schema.Literals(["FileTooLarge", "FieldTooLarge", "BodyTooLarge", "TooManyParts", "InternalError", "Parse"]), - cause: Schema.Defect -}) { +export class MultipartErrorReason extends Data.Error<{ + readonly _tag: "FileTooLarge" | "FieldTooLarge" | "BodyTooLarge" | "TooManyParts" | "InternalError" | "Parse" + readonly cause?: unknown +}> {} + +/** + * @since 4.0.0 + * @category Errors + */ +export class MultipartError extends Data.TaggedError("MultipartError")<{ + readonly reason: MultipartErrorReason +}> { + /** + * @since 4.0.0 + */ + static fromReason(reason: MultipartErrorReason["_tag"], cause?: unknown): MultipartError { + return new MultipartError({ reason: new MultipartErrorReason({ _tag: reason, cause }) }) + } + /** * @since 4.0.0 */ @@ -137,7 +152,7 @@ export class MultipartError extends Schema.ErrorClass(MultipartE * @since 4.0.0 */ override get message(): string { - return this.reason + return this.reason._tag } } @@ -349,21 +364,21 @@ function convertError(cause: MP.MultipartError): MultipartError { case "ReachedLimit": { switch (cause.limit) { case "MaxParts": { - return new MultipartError({ reason: "TooManyParts", cause }) + return MultipartError.fromReason("TooManyParts", cause) } case "MaxFieldSize": { - return new MultipartError({ reason: "FieldTooLarge", cause }) + return MultipartError.fromReason("FieldTooLarge", cause) } case "MaxPartSize": { - return new MultipartError({ reason: "FileTooLarge", cause }) + return MultipartError.fromReason("FileTooLarge", cause) } case "MaxTotalSize": { - return new MultipartError({ reason: "BodyTooLarge", cause }) + return MultipartError.fromReason("BodyTooLarge", cause) } } } default: { - return new MultipartError({ reason: "Parse", cause }) + return MultipartError.fromReason("Parse", cause) } } } @@ -423,7 +438,7 @@ class FileImpl extends PartBase implements File { this.content = Stream.fromChannel(channel) this.contentEffect = channel.pipe( collectUint8Array, - Effect.mapError((cause) => new MultipartError({ reason: "InternalError", cause })) + Effect.mapError((cause) => MultipartError.fromReason("InternalError", cause)) ) } @@ -444,7 +459,7 @@ const defaultWriteFile = (path: string, file: File) => (fs) => Effect.mapError( Stream.run(file.content, fs.sink(path)), - (cause) => new MultipartError({ reason: "InternalError", cause }) + (cause) => MultipartError.fromReason("InternalError", cause) ) ) @@ -509,7 +524,7 @@ export const toPersisted = ( }) return persisted }).pipe( - Effect.catchTag("PlatformError", (cause) => Effect.fail(new MultipartError({ reason: "InternalError", cause }))) + Effect.catchTag("PlatformError", (cause) => Effect.fail(MultipartError.fromReason("InternalError", cause))) ) class PersistedFileImpl extends PartBase implements PersistedFile { diff --git a/packages/effect/src/unstable/persistence/KeyValueStore.ts b/packages/effect/src/unstable/persistence/KeyValueStore.ts index dbb55bd680..6deaf8f084 100644 --- a/packages/effect/src/unstable/persistence/KeyValueStore.ts +++ b/packages/effect/src/unstable/persistence/KeyValueStore.ts @@ -304,7 +304,7 @@ export const layerFileSystem = ( fs.readFileString(keyPath(key)), "PlatformError", (cause) => - cause.reason === "NotFound" ? Effect.undefined : Effect.fail( + cause.reason._tag === "SystemError" && cause.reason.kind === "NotFound" ? Effect.undefined : Effect.fail( new KeyValueStoreError({ method: "get", key, @@ -318,7 +318,7 @@ export const layerFileSystem = ( fs.readFile(keyPath(key)), "PlatformError", (cause) => - cause.reason === "NotFound" ? Effect.undefined : Effect.fail( + cause.reason._tag === "SystemError" && cause.reason.kind === "NotFound" ? Effect.undefined : Effect.fail( new KeyValueStoreError({ method: "getUint8Array", key, diff --git a/packages/effect/src/unstable/socket/SocketServer.ts b/packages/effect/src/unstable/socket/SocketServer.ts index c3e570faa3..bebec6ef73 100644 --- a/packages/effect/src/unstable/socket/SocketServer.ts +++ b/packages/effect/src/unstable/socket/SocketServer.ts @@ -33,10 +33,47 @@ export type ErrorTypeId = "@effect/platform/SocketServer/SocketServerError" * @since 4.0.0 * @category errors */ -export class SocketServerError extends Data.TaggedError("SocketServerError")<{ - readonly reason: "Open" | "Unknown" +export class SocketServerOpenError extends Data.TaggedError("SocketServerOpenError")<{ readonly cause: unknown }> { + override get message(): string { + return "Open" + } +} + +/** + * @since 4.0.0 + * @category errors + */ +export class SocketServerUnknownError extends Data.TaggedError("SocketServerUnknownError")<{ + readonly cause: unknown +}> { + override get message(): string { + return "Unknown" + } +} + +/** + * @since 4.0.0 + * @category errors + */ +export type SocketServerErrorReason = SocketServerOpenError | SocketServerUnknownError + +/** + * @since 4.0.0 + * @category errors + */ +export class SocketServerError extends Data.TaggedError("SocketServerError")<{ + readonly reason: SocketServerErrorReason +}> { + constructor(props: { + readonly reason: SocketServerErrorReason + }) { + super({ + ...props, + cause: props.reason.cause + } as any) + } /** * @since 4.0.0 */ @@ -46,7 +83,7 @@ export class SocketServerError extends Data.TaggedError("SocketServerError")<{ * @since 4.0.0 */ override get message(): string { - return this.reason + return this.reason.message } } diff --git a/packages/effect/src/unstable/sql/Migrator.ts b/packages/effect/src/unstable/sql/Migrator.ts index 8e0ca56a6a..3e14f2afe1 100644 --- a/packages/effect/src/unstable/sql/Migrator.ts +++ b/packages/effect/src/unstable/sql/Migrator.ts @@ -58,12 +58,12 @@ export interface Migration { export class MigrationError extends Data.TaggedError("MigrationError")<{ readonly _tag: "MigrationError" readonly cause?: unknown - readonly reason: - | "bad-state" - | "import-error" - | "failed" - | "duplicates" - | "locked" + readonly kind: + | "BadState" + | "ImportError" + | "Failed" + | "Duplicates" + | "Locked" readonly message: string }> {} @@ -152,7 +152,7 @@ export const make = ({ Effect.catchDefect(load, (_) => Effect.fail( new MigrationError({ - reason: "import-error", + kind: "ImportError", message: `Could not import migration "${id}_${name}"\n\n${_}` }) )).pipe( @@ -163,7 +163,7 @@ export const make = ({ ? Effect.succeed(_.default?.default ?? _.default) : Effect.fail( new MigrationError({ - reason: "import-error", + kind: "ImportError", message: `Default export not found for migration "${id}_${name}"` }) ) @@ -172,7 +172,7 @@ export const make = ({ Effect.isEffect, () => new MigrationError({ - reason: "import-error", + kind: "ImportError", message: `Default export was not an Effect for migration "${id}_${name}"` }) ) @@ -187,7 +187,7 @@ export const make = ({ Effect.die( new MigrationError({ cause: error, - reason: "failed", + kind: "Failed", message: `Migration "${id}_${name}" failed` }) )) @@ -213,7 +213,7 @@ export const make = ({ if (new Set(current.map(([id]) => id)).size !== current.length) { return yield* new MigrationError({ - reason: "duplicates", + kind: "Duplicates", message: "Found duplicate migration id's" }) } @@ -238,7 +238,7 @@ export const make = ({ insertMigrations(required.map(([id, name]) => [id, name])), Effect.mapError((_) => new MigrationError({ - reason: "locked", + kind: "Locked", message: "Migrations already running" }) ) @@ -279,7 +279,7 @@ export const make = ({ const completed = yield* pipe( sql.withTransaction(run), Effect.catchTag("MigrationError", (_) => - _.reason === "locked" + _.kind === "Locked" ? Effect.as(Effect.logDebug(_.message), []) : Effect.fail(_)) ) @@ -364,7 +364,7 @@ export const fromFileSystem: (directory: string) => Loader = Effect. Fs.readDirectory(directory), (cause) => new MigrationError({ - reason: "failed", + kind: "Failed", cause, message: "Failed to read migrations directory" }) diff --git a/packages/effect/test/ConfigProvider.test.ts b/packages/effect/test/ConfigProvider.test.ts index f681f20aca..fb58b7d690 100644 --- a/packages/effect/test/ConfigProvider.test.ts +++ b/packages/effect/test/ConfigProvider.test.ts @@ -520,9 +520,9 @@ A=1`) return Effect.succeed(files[path]) } return Effect.fail( - new PlatformError.SystemError({ + PlatformError.systemError({ module: "FileSystem", - reason: "NotFound", + kind: "NotFound", method: "readFileString" }) ) @@ -530,9 +530,9 @@ A=1`) readDirectory(_path) { // For the test, we only have files, no directories return Effect.fail( - new PlatformError.SystemError({ + PlatformError.systemError({ module: "FileSystem", - reason: "NotFound", + kind: "NotFound", method: "readDirectory" }) ) diff --git a/packages/effect/test/unstable/cli/Arguments.test.ts b/packages/effect/test/unstable/cli/Arguments.test.ts index 117c9c62f6..fde5aa7681 100644 --- a/packages/effect/test/unstable/cli/Arguments.test.ts +++ b/packages/effect/test/unstable/cli/Arguments.test.ts @@ -13,7 +13,7 @@ const FileSystemLayer = FileSystem.layerNoop({ : Effect.succeed(true), stat: (path) => { if (path.includes("/non/existent/file.txt")) { - return Effect.fail(new PlatformError.BadArgument({ module: "", method: "" })) + return Effect.fail(PlatformError.badArgument({ module: "", method: "" })) } if (path.includes("workspace")) { return Effect.succeed({ type: "Directory" } as any) @@ -22,7 +22,7 @@ const FileSystemLayer = FileSystem.layerNoop({ }, access: (path) => path.includes("/non/existent/file.txt") - ? Effect.fail(new PlatformError.BadArgument({ module: "", method: "" })) + ? Effect.fail(PlatformError.badArgument({ module: "", method: "" })) : Effect.void }) const PathLayer = Path.layer diff --git a/packages/effect/test/unstable/cli/Primitive.test.ts b/packages/effect/test/unstable/cli/Primitive.test.ts index f7a7ea3795..db78b75f4f 100644 --- a/packages/effect/test/unstable/cli/Primitive.test.ts +++ b/packages/effect/test/unstable/cli/Primitive.test.ts @@ -259,7 +259,7 @@ describe("Primitive", () => { FileSystem.layerNoop({ stat: (path) => Effect.fail( - new PlatformError.BadArgument({ + PlatformError.badArgument({ module: "", method: "", description: `The specified path ${path} does not exist` @@ -284,7 +284,7 @@ describe("Primitive", () => { FileSystem.layerNoop({ stat: (path) => Effect.fail( - new PlatformError.BadArgument({ + PlatformError.badArgument({ module: "", method: "", description: `The specified path ${path} does not exist` diff --git a/packages/effect/test/unstable/http/HttpServerError.test.ts b/packages/effect/test/unstable/http/HttpServerError.test.ts new file mode 100644 index 0000000000..36e260a569 --- /dev/null +++ b/packages/effect/test/unstable/http/HttpServerError.test.ts @@ -0,0 +1,103 @@ +import { assert, describe, it } from "@effect/vitest" +import { Effect } from "effect" +import { + HttpServerError, + InternalError, + isHttpServerError, + RequestParseError, + ResponseError, + RouteNotFound, + ServeError +} from "effect/unstable/http/HttpServerError" +import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest" +import * as Respondable from "effect/unstable/http/HttpServerRespondable" +import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse" + +const makeRequest = (method: string, url: string) => HttpServerRequest.fromWeb(new Request(url, { method })) +const makeResponse = (status: number) => HttpServerResponse.empty({ status }) + +describe("HttpServerError", () => { + describe("reason messages", () => { + it("formats request reason messages", () => { + const request = makeRequest("POST", "http://example.com/widgets") + const parseError = new RequestParseError({ + request, + description: "invalid body" + }) + const routeNotFound = new RouteNotFound({ request }) + + assert.strictEqual(parseError.message, "RequestParseError (POST /widgets): invalid body") + assert.strictEqual(routeNotFound.message, "RouteNotFound (POST /widgets)") + }) + + it("formats response reason messages", () => { + const request = makeRequest("GET", "http://example.com/tea") + const response = makeResponse(418) + const responseError = new ResponseError({ + request, + response, + description: "short and stout" + }) + + assert.strictEqual(responseError.message, "ResponseError (418 GET /tea): short and stout") + }) + }) + + describe("wrapper behavior", () => { + it("delegates message and accessors", () => { + const request = makeRequest("GET", "http://example.com/ok") + const response = makeResponse(503) + const reason = new ResponseError({ request, response }) + const error = new HttpServerError({ reason }) + + assert.strictEqual(error.message, reason.message) + assert.strictEqual(error.request, request) + assert.strictEqual(error.response, response) + assert.strictEqual(error.reason, reason) + }) + + it("forwards the reason cause", () => { + const request = makeRequest("GET", "http://example.com/boom") + const cause = new Error("boom") + const reason = new InternalError({ request, cause }) + const error = new HttpServerError({ reason }) + + assert.strictEqual(reason.cause, cause) + assert.strictEqual(error.cause, cause) + }) + }) + + describe("respondable mapping", () => { + it.effect("maps reasons to status codes", () => + Effect.gen(function*() { + const request = makeRequest("GET", "http://example.com/status") + const response = makeResponse(418) + const cases: ReadonlyArray = [ + [new RequestParseError({ request }), 400], + [new RouteNotFound({ request }), 404], + [new InternalError({ request }), 500], + [new ResponseError({ request, response }), 500], + [new HttpServerError({ reason: new RequestParseError({ request }) }), 400] + ] + + for (const [respondable, status] of cases) { + const resolved = yield* Respondable.toResponse(respondable) + assert.strictEqual(resolved.status, status) + } + })) + }) + + describe("isHttpServerError", () => { + it("matches wrapper only", () => { + const request = makeRequest("GET", "http://example.com/check") + const wrapper = new HttpServerError({ + reason: new RouteNotFound({ request }) + }) + + assert.isTrue(isHttpServerError(wrapper)) + assert.isFalse(isHttpServerError(new RouteNotFound({ request }))) + assert.isFalse(isHttpServerError(new ServeError({ cause: new Error("boom") }))) + assert.isFalse(isHttpServerError({ _tag: "HttpServerError" })) + }) + }) +}) diff --git a/packages/platform-browser/src/Geolocation.ts b/packages/platform-browser/src/Geolocation.ts index 5ed141c066..81230b4070 100644 --- a/packages/platform-browser/src/Geolocation.ts +++ b/packages/platform-browser/src/Geolocation.ts @@ -41,16 +41,66 @@ export const Geolocation: ServiceMap.Service = Service * @category Errors */ export class GeolocationError extends Data.TaggedError("GeolocationError")<{ - readonly reason: "PositionUnavailable" | "PermissionDenied" | "Timeout" - readonly cause: unknown + readonly reason: GeolocationErrorReason }> { + constructor(props: { + readonly reason: GeolocationErrorReason + }) { + super({ + ...props, + cause: props.reason.cause + } as any) + } + readonly [ErrorTypeId] = ErrorTypeId override get message(): string { - return this.reason + return this.reason.message } } +/** + * @since 1.0.0 + * @category Errors + */ +export class PositionUnavailable extends Data.TaggedError("PositionUnavailable")<{ + readonly cause: unknown +}> { + override get message(): string { + return this._tag + } +} + +/** + * @since 1.0.0 + * @category Errors + */ +export class PermissionDenied extends Data.TaggedError("PermissionDenied")<{ + readonly cause: unknown +}> { + override get message(): string { + return this._tag + } +} + +/** + * @since 1.0.0 + * @category Errors + */ +export class Timeout extends Data.TaggedError("Timeout")<{ + readonly cause: unknown +}> { + override get message(): string { + return this._tag + } +} + +/** + * @since 1.0.0 + * @category Errors + */ +export type GeolocationErrorReason = PositionUnavailable | PermissionDenied | Timeout + const makeQueue = ( options: | PositionOptions & { @@ -66,10 +116,19 @@ const makeQueue = ( (position) => Queue.offerUnsafe(queue, position), (cause) => { if (cause.code === cause.PERMISSION_DENIED) { - const error = new GeolocationError({ reason: "PermissionDenied", cause }) + const error = new GeolocationError({ + reason: new PermissionDenied({ cause }) + }) Queue.failCauseUnsafe(queue, Cause.fail(error)) } else if (cause.code === cause.TIMEOUT) { - const error = new GeolocationError({ reason: "Timeout", cause }) + const error = new GeolocationError({ + reason: new Timeout({ cause }) + }) + Queue.failCauseUnsafe(queue, Cause.fail(error)) + } else if (cause.code === cause.POSITION_UNAVAILABLE) { + const error = new GeolocationError({ + reason: new PositionUnavailable({ cause }) + }) Queue.failCauseUnsafe(queue, Cause.fail(error)) } }, diff --git a/packages/platform-browser/src/Permissions.ts b/packages/platform-browser/src/Permissions.ts index 5cb97a406c..6b65538d8e 100644 --- a/packages/platform-browser/src/Permissions.ts +++ b/packages/platform-browser/src/Permissions.ts @@ -36,15 +36,50 @@ export interface Permissions { * @since 1.0.0 * @category errors */ -export class PermissionsError extends Data.TaggedError("PermissionsError")<{ - /** https://developer.mozilla.org/en-US/docs/Web/API/Permissions/query#exceptions */ - readonly reason: "InvalidStateError" | "TypeError" +export class PermissionsInvalidStateError extends Data.TaggedError("InvalidStateError")<{ readonly cause: unknown }> { + override get message(): string { + return this._tag + } +} + +/** + * @since 1.0.0 + * @category errors + */ +export class PermissionsTypeError extends Data.TaggedError("TypeError")<{ + readonly cause: unknown +}> { + override get message(): string { + return this._tag + } +} + +/** + * @since 1.0.0 + * @category errors + */ +export type PermissionsErrorReason = PermissionsInvalidStateError | PermissionsTypeError + +/** + * @since 1.0.0 + * @category errors + */ +export class PermissionsError extends Data.TaggedError("PermissionsError")<{ + readonly reason: PermissionsErrorReason +}> { + constructor(props: { readonly reason: PermissionsErrorReason }) { + super({ + ...props, + cause: props.reason.cause + } as any) + } + readonly [ErrorTypeId] = ErrorTypeId override get message(): string { - return this.reason + return this.reason.message } } @@ -69,8 +104,9 @@ export const layer: Layer.Layer = Layer.succeed( try: () => navigator.permissions.query({ name }) as Promise, catch: (cause) => new PermissionsError({ - reason: cause instanceof DOMException ? "InvalidStateError" : "TypeError", - cause + reason: cause instanceof DOMException + ? new PermissionsInvalidStateError({ cause }) + : new PermissionsTypeError({ cause }) }) }) }) diff --git a/packages/platform-bun/src/BunHttpServer.ts b/packages/platform-bun/src/BunHttpServer.ts index 29ffa434e6..f9b37dba79 100644 --- a/packages/platform-bun/src/BunHttpServer.ts +++ b/packages/platform-bun/src/BunHttpServer.ts @@ -343,28 +343,30 @@ class BunServerRequest extends Inspectable.Class implements ServerRequest.HttpSe return this.cachedCookies = Cookies.parseHeader(this.headers.cookie ?? "") } - get stream(): Stream.Stream { + get stream(): Stream.Stream { return this.source.body ? BunStream.fromReadableStream({ evaluate: () => this.source.body as any, onError: (cause) => - new Error.RequestError({ - request: this, - reason: "RequestParseError", - cause + new Error.HttpServerError({ + reason: new Error.RequestParseError({ + request: this, + cause + }) }) }) : Stream.fail( - new Error.RequestError({ - request: this, - reason: "RequestParseError", - description: "can not create stream from empty body" + new Error.HttpServerError({ + reason: new Error.RequestParseError({ + request: this, + description: "can not create stream from empty body" + }) }) ) } - private textEffect: Effect.Effect | undefined - get text(): Effect.Effect { + private textEffect: Effect.Effect | undefined + get text(): Effect.Effect { if (this.textEffect) { return this.textEffect } @@ -372,38 +374,41 @@ class BunServerRequest extends Inspectable.Class implements ServerRequest.HttpSe Effect.tryPromise({ try: () => this.source.text(), catch: (cause) => - new Error.RequestError({ - request: this, - reason: "RequestParseError", - cause + new Error.HttpServerError({ + reason: new Error.RequestParseError({ + request: this, + cause + }) }) }) )) return this.textEffect } - get json(): Effect.Effect { + get json(): Effect.Effect { return Effect.flatMap(this.text, (_) => Effect.try({ try: () => JSON.parse(_) as unknown, catch: (cause) => - new Error.RequestError({ - request: this, - reason: "RequestParseError", - cause + new Error.HttpServerError({ + reason: new Error.RequestParseError({ + request: this, + cause + }) }) })) } - get urlParamsBody(): Effect.Effect { + get urlParamsBody(): Effect.Effect { return Effect.flatMap(this.text, (_) => Effect.try({ try: () => UrlParams.fromInput(new URLSearchParams(_)), catch: (cause) => - new Error.RequestError({ - request: this, - reason: "RequestParseError", - cause + new Error.HttpServerError({ + reason: new Error.RequestParseError({ + request: this, + cause + }) }) })) } @@ -433,8 +438,8 @@ class BunServerRequest extends Inspectable.Class implements ServerRequest.HttpSe return BunMultipart.stream(this.source) } - private arrayBufferEffect: Effect.Effect | undefined - get arrayBuffer(): Effect.Effect { + private arrayBufferEffect: Effect.Effect | undefined + get arrayBuffer(): Effect.Effect { if (this.arrayBufferEffect) { return this.arrayBufferEffect } @@ -442,18 +447,19 @@ class BunServerRequest extends Inspectable.Class implements ServerRequest.HttpSe Effect.tryPromise({ try: () => this.source.arrayBuffer(), catch: (cause) => - new Error.RequestError({ - request: this, - reason: "RequestParseError", - cause + new Error.HttpServerError({ + reason: new Error.RequestParseError({ + request: this, + cause + }) }) }) )) return this.arrayBufferEffect } - get upgrade(): Effect.Effect { - return Effect.callback((resume) => { + get upgrade(): Effect.Effect { + return Effect.callback((resume) => { const deferred = Deferred.makeUnsafe>() const closeDeferred = Deferred.makeUnsafe() const semaphore = Effect.makeSemaphoreUnsafe(1) @@ -468,10 +474,11 @@ class BunServerRequest extends Inspectable.Class implements ServerRequest.HttpSe }) if (!success) { resume(Effect.fail( - new Error.RequestError({ - request: this, - reason: "RequestParseError", - description: "Not an upgradeable ServerRequest" + new Error.HttpServerError({ + reason: new Error.RequestParseError({ + request: this, + description: "Not an upgradeable ServerRequest" + }) }) )) return diff --git a/packages/platform-bun/src/BunMultipart.ts b/packages/platform-bun/src/BunMultipart.ts index 13b4f281ec..9e5bd561c2 100644 --- a/packages/platform-bun/src/BunMultipart.ts +++ b/packages/platform-bun/src/BunMultipart.ts @@ -16,7 +16,7 @@ import * as BunStream from "./BunStream.ts" export const stream = (source: Request): Stream.Stream => BunStream.fromReadableStream({ evaluate: () => source.body!, - onError: (cause) => new Multipart.MultipartError({ reason: "InternalError", cause }) + onError: (cause) => Multipart.MultipartError.fromReason("InternalError", cause) }).pipe( Stream.pipeThroughChannel(Multipart.makeChannel(Object.fromEntries(source.headers))) ) diff --git a/packages/platform-node-shared/src/NodeFileSystem.ts b/packages/platform-node-shared/src/NodeFileSystem.ts index fc148c5783..963b8b8d35 100644 --- a/packages/platform-node-shared/src/NodeFileSystem.ts +++ b/packages/platform-node-shared/src/NodeFileSystem.ts @@ -18,7 +18,7 @@ import * as Path from "node:path" import { handleErrnoException } from "./internal/utils.ts" const handleBadArgument = (method: string) => (err: unknown) => - new Error.BadArgument({ + Error.badArgument({ module: "FileSystem", method, description: (err as Error).message ?? String(err) @@ -338,10 +338,10 @@ const makeFile = (() => { (bytesWritten) => { if (bytesWritten === 0) { return Effect.fail( - new Error.SystemError({ + Error.systemError({ module: "FileSystem", method: "writeAll", - reason: "WriteZero", + kind: "WriteZero", pathOrDescriptor: this.fd, description: "write returned 0 bytes written" }) @@ -551,9 +551,9 @@ const watchNode = (path: string) => Queue.failCauseUnsafe( queue, Cause.fail( - new Error.SystemError({ + Error.systemError({ module: "FileSystem", - reason: "Unknown", + kind: "Unknown", method: "watch", pathOrDescriptor: path, cause: error diff --git a/packages/platform-node-shared/src/NodeSocketServer.ts b/packages/platform-node-shared/src/NodeSocketServer.ts index a50f562fc8..5d38b84e0c 100644 --- a/packages/platform-node-shared/src/NodeSocketServer.ts +++ b/packages/platform-node-shared/src/NodeSocketServer.ts @@ -60,8 +60,9 @@ export const make = Effect.fnUntraced(function*( }).pipe( Effect.raceFirst(Effect.mapError(Deferred.await(errorDeferred), (err) => new SocketServer.SocketServerError({ - reason: "Open", - cause: err + reason: new SocketServer.SocketServerOpenError({ + cause: err + }) }))) ) @@ -187,8 +188,9 @@ export const makeWebSocket: ( server.once("error", (error) => { resume(Effect.fail( new SocketServer.SocketServerError({ - reason: "Open", - cause: error + reason: new SocketServer.SocketServerOpenError({ + cause: error + }) }) )) }) diff --git a/packages/platform-node-shared/src/NodeStdio.ts b/packages/platform-node-shared/src/NodeStdio.ts index 97b052fec8..0eb1868d5b 100644 --- a/packages/platform-node-shared/src/NodeStdio.ts +++ b/packages/platform-node-shared/src/NodeStdio.ts @@ -2,7 +2,7 @@ * @since 1.0.0 */ import * as Layer from "effect/Layer" -import { SystemError } from "effect/PlatformError" +import { systemError } from "effect/PlatformError" import * as Stdio from "effect/Stdio" import { fromWritable } from "./NodeSink.ts" import { fromReadable } from "./NodeStream.ts" @@ -17,30 +17,30 @@ export const layer: Layer.Layer = Layer.succeed( stdout: fromWritable({ evaluate: () => process.stdout, onError: (cause) => - new SystemError({ + systemError({ module: "Stdio", method: "stdout", - reason: "Unknown", + kind: "Unknown", cause }) }), stderr: fromWritable({ evaluate: () => process.stderr, onError: (cause) => - new SystemError({ + systemError({ module: "Stdio", method: "stderr", - reason: "Unknown", + kind: "Unknown", cause }) }), stdin: fromReadable({ evaluate: () => process.stdin, onError: (cause) => - new SystemError({ + systemError({ module: "Stdio", method: "stdin", - reason: "Unknown", + kind: "Unknown", cause }), closeOnDone: false diff --git a/packages/platform-node-shared/src/NodeTerminal.ts b/packages/platform-node-shared/src/NodeTerminal.ts index aa1d1f163d..bcb5116849 100644 --- a/packages/platform-node-shared/src/NodeTerminal.ts +++ b/packages/platform-node-shared/src/NodeTerminal.ts @@ -4,7 +4,7 @@ import type * as Cause from "effect/Cause" import * as Effect from "effect/Effect" import * as Layer from "effect/Layer" -import * as PlatformError from "effect/PlatformError" +import { badArgument, type PlatformError } from "effect/PlatformError" import * as Predicate from "effect/Predicate" import * as Queue from "effect/Queue" import * as RcRef from "effect/RcRef" @@ -76,12 +76,12 @@ export const make: ( const display = (prompt: string) => Effect.uninterruptible( - Effect.callback((resume) => { + Effect.callback((resume) => { stdout.write(prompt, (err) => Predicate.isNullish(err) ? resume(Effect.void) : resume(Effect.fail( - new PlatformError.BadArgument({ + badArgument({ module: "Terminal", method: "display", description: "Failed to write prompt to stdout", diff --git a/packages/platform-node-shared/src/internal/utils.ts b/packages/platform-node-shared/src/internal/utils.ts index e4b5f6d659..2fb7f8e53a 100644 --- a/packages/platform-node-shared/src/internal/utils.ts +++ b/packages/platform-node-shared/src/internal/utils.ts @@ -1,5 +1,5 @@ -import type { PlatformError, SystemErrorReason } from "effect/PlatformError" -import { SystemError } from "effect/PlatformError" +import type { SystemError, SystemErrorKind } from "effect/PlatformError" +import * as PlatformError from "effect/PlatformError" import type { PathLike } from "node:fs" /** @internal */ @@ -7,8 +7,8 @@ export const handleErrnoException = (module: SystemError["module"], method: stri ( err: NodeJS.ErrnoException, [path]: [path: PathLike | number, ...args: Array] -): PlatformError => { - let reason: SystemErrorReason = "Unknown" +): PlatformError.PlatformError => { + let reason: SystemErrorKind = "Unknown" switch (err.code) { case "ENOENT": @@ -40,8 +40,8 @@ export const handleErrnoException = (module: SystemError["module"], method: stri break } - return new SystemError({ - reason, + return PlatformError.systemError({ + kind: reason, module, method, pathOrDescriptor: path as string | number, diff --git a/packages/platform-node-shared/test/NodeChildProcessSpawner.test.ts b/packages/platform-node-shared/test/NodeChildProcessSpawner.test.ts index c244b4af06..73dd7f6525 100644 --- a/packages/platform-node-shared/test/NodeChildProcessSpawner.test.ts +++ b/packages/platform-node-shared/test/NodeChildProcessSpawner.test.ts @@ -619,8 +619,8 @@ describe("NodeChildProcessSpawner", () => { assert.deepStrictEqual( result, - new PlatformError.SystemError({ - reason: "PermissionDenied", + PlatformError.systemError({ + kind: "PermissionDenied", module: "ChildProcess", method: "spawn", pathOrDescriptor: "./no-permissions.sh ", diff --git a/packages/platform-node-shared/test/NodeFileSystem.test.ts b/packages/platform-node-shared/test/NodeFileSystem.test.ts index 4ad7a17745..169e07f936 100644 --- a/packages/platform-node-shared/test/NodeFileSystem.test.ts +++ b/packages/platform-node-shared/test/NodeFileSystem.test.ts @@ -44,7 +44,7 @@ describe("FileSystem", () => { }) ) const error = yield* Effect.flip(fs.stat(dir)) - assert(error._tag === "PlatformError" && error.reason === "NotFound") + assert(error.reason._tag === "SystemError" && error.reason.kind === "NotFound") }))) it("truncate", () => diff --git a/packages/platform-node/src/NodeHttpServer.ts b/packages/platform-node/src/NodeHttpServer.ts index 3a9dfe13fd..6e8b60ea52 100644 --- a/packages/platform-node/src/NodeHttpServer.ts +++ b/packages/platform-node/src/NodeHttpServer.ts @@ -24,11 +24,11 @@ import type { HttpMethod } from "effect/unstable/http/HttpMethod" import type * as Middleware from "effect/unstable/http/HttpMiddleware" import type * as HttpPlatform from "effect/unstable/http/HttpPlatform" import * as HttpServer from "effect/unstable/http/HttpServer" -import type { HttpServerError } from "effect/unstable/http/HttpServerError" import { causeResponse, clientAbortFiberId, - RequestError, + HttpServerError, + RequestParseError, ResponseError, ServeError } from "effect/unstable/http/HttpServerError" @@ -245,10 +245,11 @@ class ServerRequestImpl extends NodeHttpIncomingMessage impleme remoteAddressOverride?: string ) { super(source, (cause) => - new RequestError({ - request: this, - reason: "RequestParseError", - cause + new HttpServerError({ + reason: new RequestParseError({ + request: this, + cause + }) }), remoteAddressOverride) this[Request.TypeId] = Request.TypeId this.response = response @@ -326,10 +327,11 @@ class ServerRequestImpl extends NodeHttpIncomingMessage impleme get upgrade(): Effect.Effect { return this.upgradeEffect ?? Effect.fail( - new RequestError({ - request: this, - reason: "RequestParseError", - description: "not an upgradeable ServerRequest" + new HttpServerError({ + reason: new RequestParseError({ + request: this, + description: "not an upgradeable ServerRequest" + }) }) ) } @@ -469,11 +471,13 @@ const handleResponse = ( return Effect.tryPromise({ try: (signal) => pipeline(body.body as any, nodeResponse, { signal, end: true }), catch: (cause) => - new ResponseError({ - request, - response, - description: "Error writing raw response", - cause + new HttpServerError({ + reason: new ResponseError({ + request, + response, + description: "Error writing raw response", + cause + }) }) }).pipe( Effect.interruptible, @@ -507,11 +511,13 @@ const handleResponse = ( .pipe(nodeResponse) .on("error", (cause) => { resume(Effect.fail( - new ResponseError({ - request, - response, - description: "Error writing FormData response", - cause + new HttpServerError({ + reason: new ResponseError({ + request, + response, + description: "Error writing FormData response", + cause + }) }) )) }) diff --git a/packages/platform-node/src/NodeMultipart.ts b/packages/platform-node/src/NodeMultipart.ts index a521a4c0b0..2312f41ac1 100644 --- a/packages/platform-node/src/NodeMultipart.ts +++ b/packages/platform-node/src/NodeMultipart.ts @@ -53,7 +53,7 @@ export const persisted = ( Multipart.toPersisted(stream(source, headers), (path, file) => Effect.tryPromise({ try: (signal) => NodeStreamP.pipeline((file as FileImpl).file, NFS.createWriteStream(path), { signal }), - catch: (cause) => new Multipart.MultipartError({ reason: "InternalError", cause }) + catch: (cause) => Multipart.MultipartError.fromReason("InternalError", cause) })) /** @@ -120,10 +120,10 @@ class FileImpl extends PartBase implements Multipart.File { this.contentType = file.info.contentType this.content = NodeStream.fromReadable({ evaluate: () => file, - onError: (cause) => new Multipart.MultipartError({ reason: "InternalError", cause }) + onError: (cause) => Multipart.MultipartError.fromReason("InternalError", cause) }) this.contentEffect = NodeStream.toUint8Array(() => file, { - onError: (cause) => new Multipart.MultipartError({ reason: "InternalError", cause }) + onError: (cause) => Multipart.MultipartError.fromReason("InternalError", cause) }) } @@ -143,21 +143,21 @@ function convertError(cause: MP.MultipartError): Multipart.MultipartError { case "ReachedLimit": { switch (cause.limit) { case "MaxParts": { - return new Multipart.MultipartError({ reason: "TooManyParts", cause }) + return Multipart.MultipartError.fromReason("TooManyParts", cause) } case "MaxFieldSize": { - return new Multipart.MultipartError({ reason: "FieldTooLarge", cause }) + return Multipart.MultipartError.fromReason("FieldTooLarge", cause) } case "MaxPartSize": { - return new Multipart.MultipartError({ reason: "FileTooLarge", cause }) + return Multipart.MultipartError.fromReason("FileTooLarge", cause) } case "MaxTotalSize": { - return new Multipart.MultipartError({ reason: "BodyTooLarge", cause }) + return Multipart.MultipartError.fromReason("BodyTooLarge", cause) } } } default: { - return new Multipart.MultipartError({ reason: "Parse", cause }) + return Multipart.MultipartError.fromReason("Parse", cause) } } } diff --git a/packages/platform-node/test/NodeHttpServer.test.ts b/packages/platform-node/test/NodeHttpServer.test.ts index 0a6843b827..2209167442 100644 --- a/packages/platform-node/test/NodeHttpServer.test.ts +++ b/packages/platform-node/test/NodeHttpServer.test.ts @@ -119,7 +119,7 @@ describe("HttpServer", () => { return HttpServerResponse.empty() }).pipe( Effect.catchTag("MultipartError", (error) => - error.reason === "FileTooLarge" ? + error.reason._tag === "FileTooLarge" ? Effect.succeed(HttpServerResponse.empty({ status: 413 })) : Effect.fail(error)) ) @@ -147,7 +147,7 @@ describe("HttpServer", () => { return HttpServerResponse.empty() }).pipe( Effect.catchTag("MultipartError", (error) => - error.reason === "FieldTooLarge" ? + error.reason._tag === "FieldTooLarge" ? Effect.succeed(HttpServerResponse.empty({ status: 413 })) : Effect.fail(error)) ) diff --git a/packages/sql/mysql2/src/MysqlMigrator.ts b/packages/sql/mysql2/src/MysqlMigrator.ts index 73af79193d..92fbe1b653 100644 --- a/packages/sql/mysql2/src/MysqlMigrator.ts +++ b/packages/sql/mysql2/src/MysqlMigrator.ts @@ -50,7 +50,7 @@ export const run: ( // .replace(/\n{2,}/gm, "\n\n") // .trim() // }).pipe( - // Effect.mapError((error) => new Migrator.MigrationError({ reason: "failed", message: error.message })) + // Effect.mapError((error) => new Migrator.MigrationError({ kind: "Failed", message: error.message })) // ) // // const dumpSchema = mysqlDump(["--no-data"]) @@ -70,7 +70,7 @@ export const run: ( // yield* fs.makeDirectory(path.dirname(file), { recursive: true }) // yield* fs.writeFileString(file, dump) // }).pipe( - // Effect.mapError((error) => new Migrator.MigrationError({ reason: "failed", message: error.message })) + // Effect.mapError((error) => new Migrator.MigrationError({ kind: "Failed", message: error.message })) // ) // // return dumpFile(path) diff --git a/packages/sql/pg/src/PgMigrator.ts b/packages/sql/pg/src/PgMigrator.ts index 114aaa1e1f..5f833bcdce 100644 --- a/packages/sql/pg/src/PgMigrator.ts +++ b/packages/sql/pg/src/PgMigrator.ts @@ -50,7 +50,7 @@ export const run: ( // .replace(/\n{2,}/gm, "\n\n") // .trim() // }).pipe( - // Effect.mapError((error) => new Migrator.MigrationError({ reason: "failed", message: error.message })) + // Effect.mapError((error) => new Migrator.MigrationError({ kind: "Failed", message: error.message })) // ) // // const pgDumpSchema = pgDump(["--schema-only"]) @@ -74,7 +74,7 @@ export const run: ( // yield* fs.makeDirectory(path_.dirname(path), { recursive: true }) // yield* fs.writeFileString(path, dump) // }).pipe( - // Effect.mapError((error) => new Migrator.MigrationError({ reason: "failed", message: error.message })) + // Effect.mapError((error) => new Migrator.MigrationError({ kind: "Failed", message: error.message })) // ) // // return pgDumpFile(path) diff --git a/packages/sql/sqlite-bun/src/SqliteMigrator.ts b/packages/sql/sqlite-bun/src/SqliteMigrator.ts index 203069125c..113db26bbb 100644 --- a/packages/sql/sqlite-bun/src/SqliteMigrator.ts +++ b/packages/sql/sqlite-bun/src/SqliteMigrator.ts @@ -35,7 +35,7 @@ export const run: ( // .replace(/\n{2,}/gm, "\n\n") // .trim() // }).pipe( - // Effect.mapError((error) => new Migrator.MigrationError({ reason: "failed", message: error.message })) + // Effect.mapError((error) => new Migrator.MigrationError({ kind: "Failed", message: error.message })) // ) // // const dumpSchema = dump([".schema"]) @@ -59,7 +59,7 @@ export const run: ( // yield* fs.makeDirectory(path.dirname(file), { recursive: true }) // yield* fs.writeFileString(file, dump) // }).pipe( - // Effect.mapError((error) => new Migrator.MigrationError({ reason: "failed", message: error.message })) + // Effect.mapError((error) => new Migrator.MigrationError({ kind: "Failed", message: error.message })) // ) // // return dumpFile(path) diff --git a/packages/sql/sqlite-node/src/SqliteMigrator.ts b/packages/sql/sqlite-node/src/SqliteMigrator.ts index 68ab34d8a7..5f8b2ed661 100644 --- a/packages/sql/sqlite-node/src/SqliteMigrator.ts +++ b/packages/sql/sqlite-node/src/SqliteMigrator.ts @@ -35,7 +35,7 @@ export const run: ( // .replace(/\n{2,}/gm, "\n\n") // .trim() // }).pipe( - // Effect.mapError((error) => new Migrator.MigrationError({ reason: "failed", message: error.message })) + // Effect.mapError((error) => new Migrator.MigrationError({ kind: "Failed", message: error.message })) // ) // // const dumpSchema = dump([".schema"]) @@ -59,7 +59,7 @@ export const run: ( // yield* fs.makeDirectory(path.dirname(file), { recursive: true }) // yield* fs.writeFileString(file, dump) // }).pipe( - // Effect.mapError((error) => new Migrator.MigrationError({ reason: "failed", message: error.message })) + // Effect.mapError((error) => new Migrator.MigrationError({ kind: "Failed", message: error.message })) // ) // // return dumpFile(path)