|
4 | 4 | import * as Effect from "../../Effect.ts" |
5 | 5 | import * as Layer from "../../Layer.ts" |
6 | 6 | import { hasProperty } from "../../Predicate.ts" |
7 | | -import type * as Schema from "../../Schema.ts" |
| 7 | +import * as Schema from "../../Schema.ts" |
8 | 8 | import { Scope } from "../../Scope.ts" |
9 | 9 | import * as ServiceMap from "../../ServiceMap.ts" |
10 | 10 | import type { unhandled } from "../../Types.ts" |
@@ -292,6 +292,51 @@ export const Service = < |
292 | 292 | return self |
293 | 293 | } |
294 | 294 |
|
| 295 | +/** |
| 296 | + * Implement a middleware Layer that transforms `SchemaError`'s. |
| 297 | + * |
| 298 | + * ```ts |
| 299 | + * import { Effect, Schema } from "effect" |
| 300 | + * import { HttpApiMiddleware } from "effect/unstable/httpapi" |
| 301 | + * |
| 302 | + * export class CustomError extends Schema.TaggedErrorClass<CustomError>()("CustomError", {}) {} |
| 303 | + * |
| 304 | + * export class ErrorHandler extends HttpApiMiddleware.Service<ErrorHandler>()("api/ErrorHandler", { |
| 305 | + * error: CustomError |
| 306 | + * }) {} |
| 307 | + * |
| 308 | + * export const ErrorHandlerLayer = HttpApiMiddleware.layerSchemaErrorTransform( |
| 309 | + * ErrorHandler, |
| 310 | + * (schemaError) => |
| 311 | + * Effect.log("Got SchemaError", schemaError).pipe( |
| 312 | + * Effect.andThen(Effect.fail(new CustomError())) |
| 313 | + * ) |
| 314 | + * ) |
| 315 | + * ``` |
| 316 | + * |
| 317 | + * @since 4.0.0 |
| 318 | + * @category SchemaError transform |
| 319 | + */ |
| 320 | +export const layerSchemaErrorTransform = <Id, E extends Schema.Top, Requires>( |
| 321 | + service: ServiceMap.Service<Id, HttpApiMiddleware<never, E, Requires>>, |
| 322 | + transform: ( |
| 323 | + error: Schema.SchemaError, |
| 324 | + context: { readonly endpoint: HttpApiEndpoint.AnyWithProps; readonly group: HttpApiGroup.AnyWithProps } |
| 325 | + ) => Effect.Effect<HttpServerResponse, E["Type"] | Schema.SchemaError, Requires | HttpRouter.Provided> |
| 326 | +): Layer.Layer<Id> => |
| 327 | + Layer.succeed( |
| 328 | + service, |
| 329 | + (httpEffect, options) => |
| 330 | + Effect.catch( |
| 331 | + httpEffect, |
| 332 | + (e): Effect.Effect< |
| 333 | + HttpServerResponse, |
| 334 | + unhandled | Schema.SchemaError | E["Type"], |
| 335 | + Requires | HttpRouter.Provided |
| 336 | + > => Schema.isSchemaError(e) ? transform(e, options) : Effect.fail(e) |
| 337 | + ) |
| 338 | + ) |
| 339 | + |
295 | 340 | /** |
296 | 341 | * @since 4.0.0 |
297 | 342 | * @category client |
|
0 commit comments