Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const Archetype = require('archetype');
- const UserType = new Archetype({
- name: { $type: 'string' },
- age: { $type: 'number' }
- }).compile('UserType');
- // Prints 'age: Could not cast "not a number" to number'
- throwError().catch(error => console.error(error.message));
- catchError().catch(() => { console.log('unexpected error'); });
- async function throwError() {
- // `new UserType()` throws an error if casting fails. In this case,
- // archetype will fail to coerce `age` into a number. This exception
- // will bubble up to the promise this async function returns.
- new UserType({ name: 'test', age: 'not a number' });
- // This means you don't need to do an `if (error != null) {}` check
- // here. Leave that masochism in Golang where it belongs.
- }
- async function catchError() {
- try {
- new UserType({ name: { hello: 'world' } });
- } catch (error) {
- // Prints 'Caught name: Could not cast "[object Object]" to string'
- console.log('Caught', error.message);
- }
- // Execution continues normally, no error. Archetype throws errors
- // by default in order to better integrate with async/await, because
- // usually malformed input should cause your business logic should fail
- // fast. But if you don't want to bubble up the error, try/catch is
- // the way to go.
- }
Add Comment
Please, Sign In to add comment