try
$try
This is a conditional operator that evaluates a predicate for whether it throws/rejects.
If the predicate does not throw, $try will return the result of invoking any provided success action with the predicate result. If not provided, the default success action will simply return the predicate result.
If the predicate rejects/throws, $try will return the result of invoking the failure action with the error returned. The default failure action will return undefined. Since the predicate result is an error, the failure action is best used to either intercept errors and return a default value, or to propagate or wrap the error.
This processor can act as a constraint if the success or failure actions throw when triggered.
Parameters
predicate(processor, optional): Executed and observed for throw/rejection.success(processor, optional): Invoked with the predicate result if it did not throw. Default: returns predicate result.failure(processor, optional): Invoked with the thrown error if the predicate threw. Default: returns undefined.
Array form: {$try: [predicate, success, failure]}
Object form: {$try: {predicate: ..., success: ..., failure: ...}}
Example
// Attempt JSON parsing, fall back to raw string on failure
new Schema('string').normalizer({
$try: ['$json-decode', null, (err) => err.input]
})
// Attempt to parse a number, silently drop value on error
new Schema('string').normalizer({
$try: ['$number']
})