Skip to content
Myr

SchemaValidationError.ts

This file

Path

source/errors/SchemaValidationError.ts

33 lines · 1.1 KiB · TypeScript

Last changed by

Allow customizing error names in TypeScriptSindre Sorhusbefore adoption52b8f93

History of this file

Take it

Add Standard Schema validation for `.json()` (#830)Sindre Sorhusbefore adoption94741a9

lines 1–3why, one step back
1import type {StandardSchemaV1Issue} from '../types/standard-schema.js';
23/**

Readme tweaksSindre Sorhusbefore adoption7f2eade

line 4why, one step back
4The error thrown when [Standard Schema](https://github.com/standard-schema/standard-schema) validation fails in `.json(schema)`. It has an `issues` property with the validation issues from the schema.

Add Standard Schema validation for `.json()` (#830)Sindre Sorhusbefore adoption94741a9

lines 5–25why, one step back
5
6This error intentionally does not extend `KyError` because it does not represent a failure in Ky's HTTP lifecycle. The request succeeded; the user's schema rejected the data. As such, it is not matched by `isKyError()`.78@example9```10import ky, {SchemaValidationError} from 'ky';11import {z} from 'zod';1213const userSchema = z.object({name: z.string()});1415try {16 const user = await ky('/api/user').json(userSchema);17 console.log(user.name);18} catch (error) {19 if (error instanceof SchemaValidationError) {20 console.error(error.issues);21 }22}23```24*/25export class SchemaValidationError extends Error {

Allow customizing error names in TypeScriptSindre Sorhusbefore adoption52b8f93

line 26why, one step back
26 override name = 'SchemaValidationError';

Add Standard Schema validation for `.json()` (#830)Sindre Sorhusbefore adoption94741a9

lines 27–33why, one step back
27 readonly issues: readonly StandardSchemaV1Issue[];
2829 constructor(issues: readonly StandardSchemaV1Issue[]) {30 super('Response schema validation failed');31 this.issues = issues;32 }33}