Add note about custom errors
Okay, so if you pass a filterWith rule, that function should return true|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 }.
I propose that we should include a way to define custom errors when filterWith, like so:
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 message field. Will definitely try that out. whitelister is awesome btw. Simple yet powerful enough to get the job done and done it right! 👍
@motss thank you!
I haven't implemented message field yet. But I could do so if it would help your use case.
😄
@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 filterWith:
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 message would need to be a function; but it could still be an option to let you choose what the default error message is.
@davidpaulhunt This totally fit my purpose. 👍