Validation().error()
Adds state callbacks which will be invoked when an error occurs in predicate functions or in other state callbacks during validation process.
Syntax
Validation().error(callback1, callback2, /* ..., */ callbackN)Validation().error([callback1, callback2, /* ..., */ callbackN])Validation().error(callback1, [callback2, /* ..., */ callbackN])Validation().error(callback1, [[callback2], /* ..., */ callbackN])Validation().error([callback1, callback2], /* ..., */ callbackN)Validation().error([[callback1], callback2], /* ..., */ callbackN)
Parameters
-
callback1, ..., callbackN
Functions to add. The callback functions will be called with the following arguments:-
error
AnError
object. -
next
A function to invoke in case theerror
is not needed to be catched and instead is needed to be passed further.
-
Return value
The Validation
object.
Exceptions
If anything other than a function was passed in or an Array
that contains not a function the corresponding error will be thrown.
Description
Accepts functions or arrays of functions of any nesting level or both in any combination.
Adds error state callbacks to the Validation
object. Once the Validation
is in the error state, the callbacks will be invoked one by one in the order they were added. The main purpose of error state callbacks is to perform side effects related to the error state.
When validating grouping Validation
objects, unlike other state callbacks, error state callbacks of their grouped validations will not be triggered.
This method catches errors that occur in predicate functions and in their associated state callbacks and other state callbacks of the Validation
(and its grouped validations) when the Validation.validate()
method gets invoked (or the Validation
object is used as an event handler or middleware).
If you want to just perform side effects and not to catch the error on this level, it is possible to forward the error further to return a rejected Promise
from the Validation().validate()
method or from the middleware by calling the function passed into a callback as the parameter next
. This may be used to trigger the Express
error handling middleware. If you add several error state callbacks in a row, calling the function next
in only one of them is enough.
Also see “Error handling”.
Examples
Catching an error in a state callback of a Validation
import { Validation } from "isomorphic-validation";
// predicate functionconst isMeaningOfLife = (value) => value === 42;
// state callbacksconst faultyCallback = (res) => { res.a.b.c }; // accessing a non existing propertyconst errorHandler = ({message}) => { console.log(message); };
const validatableObject = { value: 42 };
const validation = Validation(validatableObject) .constraint(isMeaningOfLife) .validated(faultyCallback) .error(errorHandler);
await validation.validate();await validation.validate();
// Output://// Cannot read properties of undefined (reading 'b')// Cannot read properties of undefined (reading 'b')
Catching an error in a predicate function
import { Validation } from "isomorphic-validation";
// predicate functionconst faultyCheckEmail = (value) => fetch(`http://your-app.com/check-email/?q=${value}`) .then(res => res.json());
// state callbacksconst validStateCallback = () => { console.log('The e-mail is available.'); };const invalidStateCallback = () => { console.log('The e-mail is taken.'); };const errorHandler = ({message}) => { console.log(message); };
const validatableObject = { value: 'a@a.a' };
const validation = Validation(validatableObject) .constraint(faultyCheckEmail) .valid(validStateCallback) .invalid(invalidStateCallback) .error(errorHandler);
await validation.validate();await validation.validate();
// Output://// fetch failed// fetch failed
Catching an error in a state callback of a Predicate
import { Validation, Predicate } from "isomorphic-validation";
// predicate functionconst isMeaningOfLife = (value) => value === 42;
// state callbacksconst faultyCallback = (res) => { res.a.b.c }; // accessing a non existing propertyconst errorHandler = ({message}) => { console.log(message); };
const validatableObject = { value: 42 };
const validation = Validation(validatableObject) .constraint( Predicate(isMeaningOfLife) .validated(faultyCallback) ) .error(errorHandler);
await validation.validate();await validation.validate();
// Output://// Cannot read properties of undefined (reading 'b')// Cannot read properties of undefined (reading 'b')
Error forwarding
import { Validation } from "isomorphic-validation";
const { log } = console;
// predicate functions
const faultyCheckEmail = (value) => fetch(`http://your-app.com/check-email/?q=${value}`) .then(res => res.json());
const areAllowedChars = (value) => /^[A-Za-z\s]+$/.test(value);
// state callbacks
const emailValidHandler = () => { log('The e-mail is available.'); };const emailInvalidHandler = () => { log('The e-mail is taken.'); };const emailErrorHandler = ({message}) => { log('e-mail:', message, '\n'); };
const nameValidHandler = () => { log('The name has valid characters.'); };const nameInvalidHandler = () => { log('The name has invalid characters.'); };const nameErrorHandler = ({message}) => { log('name:', message); };
const groupErrorHandler = (err, next) => { log('group:', err.message); next() };const promiseRejectHandler = ({ message }) => { log('Promise:', message, '\n'); };
// validatable objectsconst email = { value: 'a@a.a' };const name = { value: 'John Doe' };
const emailValidation = Validation(email) .constraint(faultyCheckEmail) .valid(emailValidHandler) .invalid(emailInvalidHandler) .error(emailErrorHandler);
const nameValidation = Validation(name) .constraint(areAllowedChars) .valid(nameValidHandler) .invalid(nameInvalidHandler) .error(nameErrorHandler);
const validation = Validation.group(emailValidation, nameValidation) .error(groupErrorHandler);
// catching the forwarded errorawait validation.validate().catch(promiseRejectHandler); // groupErrorHandler and promiseRejectHandler will be called
await emailValidation.validate(); // emailErrorHandler will be calledawait nameValidation.validate(); // nameValidHandler will be called (no errors)
// Output://// group: fetch failed// Promise: fetch failed//// e-mail: fetch failed//// The name has valid characters.