-
Notifications
You must be signed in to change notification settings - Fork 2
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
Add note about custom errors #6
Comments
I propose that we should include a way to define custom errors when const schema = {
first_name: { type: 'string', required: true, error: new TypeError('first_name is not defined') },
}; Thoughts, anyone? |
@motss oh, interesting! So, internally, fields throw errors that are caught specifically by type, so it might take more effort to permit custom error types. Could you get what you need if it was possible to define the error message? For example: const schema = {
first_name: { type: 'string', required: true, message: 'first_name is not defined' },
}; |
@davidpaulhunt Missed out that |
@motss thank you! I haven't implemented 😄 |
@davidpaulhunt I see. But it'd be nice if it can be function, like so: // message: val => { ... },
const schema = {
first_name: {
type: 'string',
required: true,
message: val => `first_name (${val}) is invalid`,
},
age: {
type: 'integer',
required: true,
min: 0,
max: 999,
message: (val) => {
if (val < 0 || val > 999) return `Invalid age (${val}). Please specify an age in between 0 and 999`;
return 'Please specify a valid age';
},
},
}; In this case, I can return the invalid value along with the error message. |
@davidpaulhunt Any update on this? |
@motss your example of above can already be implemented with const schema = {
age: {
type: 'integer',
required: true,
min: 0,
max: 999,
filterWith: (val) => {
if (val < 0 || val > 999) throw new Error(`Invalid age (${val}). Please specify an age in between 0 and 999`);
if (someOtherCondition) {
throw new Error('Please specify a valid age');
}
return true
},
},
}; So I don't think |
@davidpaulhunt This totally fit my purpose. 👍 |
Okay, so if you pass a
filterWith
rule, that function should returntrue|false
.However, you can throw a custom error in that function instead. It's just that the customer error needs to implement
toJSON
and return{ field, message }
.The text was updated successfully, but these errors were encountered: