Guest User

Untitled

a guest
Nov 19th, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. const Archetype = require('archetype');
  2.  
  3. const UserType = new Archetype({
  4. name: { $type: 'string' },
  5. age: { $type: 'number' }
  6. }).compile('UserType');
  7.  
  8. // Prints 'age: Could not cast "not a number" to number'
  9. throwError().catch(error => console.error(error.message));
  10.  
  11. catchError().catch(() => { console.log('unexpected error'); });
  12.  
  13. async function throwError() {
  14. // `new UserType()` throws an error if casting fails. In this case,
  15. // archetype will fail to coerce `age` into a number. This exception
  16. // will bubble up to the promise this async function returns.
  17. new UserType({ name: 'test', age: 'not a number' });
  18. // This means you don't need to do an `if (error != null) {}` check
  19. // here. Leave that masochism in Golang where it belongs.
  20. }
  21.  
  22. async function catchError() {
  23. try {
  24. new UserType({ name: { hello: 'world' } });
  25. } catch (error) {
  26. // Prints 'Caught name: Could not cast "[object Object]" to string'
  27. console.log('Caught', error.message);
  28. }
  29. // Execution continues normally, no error. Archetype throws errors
  30. // by default in order to better integrate with async/await, because
  31. // usually malformed input should cause your business logic should fail
  32. // fast. But if you don't want to bubble up the error, try/catch is
  33. // the way to go.
  34. }
Add Comment
Please, Sign In to add comment