Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simple custom error message #948

Closed
SlavenIvanov opened this issue May 10, 2024 · 1 comment
Closed

Simple custom error message #948

SlavenIvanov opened this issue May 10, 2024 · 1 comment

Comments

@SlavenIvanov
Copy link

SlavenIvanov commented May 10, 2024

Request a feature

Is it possible to add a simple error message to a field?

🤷 Motivation

It would be great to simply setup a default error message.

💡 Solution

export const project = type({
	name: "string: errorMsg:'Name must be a string 👽'" // or anything that can solve this issue.
})
@ssalbdivad
Copy link
Member

Good question! I'm working on the docs for v2 now but error messages are very customizable!

Here are a few options for this situation:

import { type } from "arktype"

export const project = type({
	name: ["string", "@", "a string 👽"]
})

const out = project({ name: 5 })

if (out instanceof type.errors) {
	// 'name must be a string 👽 (was number)'
	console.log(out.summary)
} else {
	console.log(`Hi, ${out.name}!`)
}

const name = type("string").describe("a string 👽")

// this is equivalent to above
const project2 = type({ name })

Note that what you pass to describe is essentially the ___ in must be ___. This allows error messages to compose better for unions, intersections etc.

There are ways to customize the full structure of the message but I will get into those more in the upcoming docs!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: Done (merged or closed)
Development

No branches or pull requests

2 participants