Skip to content

Instantly share code, notes, and snippets.

@vkarpov15
Created November 18, 2017 01:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vkarpov15/f10b560468f49166bcc14c6e41bb755e to your computer and use it in GitHub Desktop.
Save vkarpov15/f10b560468f49166bcc14c6e41bb755e to your computer and use it in GitHub Desktop.
Async/Await with Archetype
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.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment