Open History to see the last commit
1/**
2 * @since 4.0.0
3 */
4import * as Data from "./Data.ts"
5import * as Predicate from "./Predicate.ts"
6import type { Issue } from "./SchemaIssue.ts"
7
8const TypeId = "~effect/SchemaError/SchemaError"
9
10/**
11 * Error thrown (or returned as the error channel value) when schema decoding
12 * or encoding fails.
13 *
14 * **Details**
15 *
16 * The `issue` field contains a structured {@link Issue} tree describing
17 * every validation failure, including the path to the problematic value,
18 * expected types, and actual values received. `message` renders the issue tree
19 * as a human-readable string.
20 *
21 * Use {@link isSchemaError} to narrow an unknown value to `SchemaError`.
22 *
23 * **Example** (Catching a SchemaError)
24 *
25 * ```ts
26 * import { Schema } from "effect"
27 *
28 * try {
29 * Schema.decodeUnknownSync(Schema.Number)("not a number")
30 * } catch (err) {
31 * if (Schema.isSchemaError(err)) {
32 * console.log(err.message)
33 * // Expected number, actual "not a number"
34 * }
35 * }
36 * ```
37 *
38 * @category errors
39 * @since 4.0.0
40 */
41export class SchemaError extends Data.TaggedError("SchemaError")<{
42 readonly issue: Issue
43}> {
44 readonly [TypeId]: typeof TypeId = TypeId
45 constructor(issue: Issue) {
46 super({ issue })
47 }
48 override get message() {
49 return this.issue.toString()
50 }
51 override toString() {
52 return `SchemaError(${this.message})`
53 }
54}
55
56/**
57 * Returns `true` if `u` is a {@link SchemaError}.
58 *
59 * @category guards
60 * @since 4.0.0
61 */
62export function isSchemaError(u: unknown): u is SchemaError {
63 return Predicate.hasProperty(u, TypeId) && u[TypeId] === TypeId
64}