Advertisement
Guest User

Untitled

a guest
Jan 22nd, 2017
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. /* jshint esversion: 6, node: true */
  2.  
  3. 'use strict';
  4.  
  5. /** Sample code using the promisified service API. */
  6.  
  7. const avro = require('avsc');
  8. const promisify = require('./promisify');
  9.  
  10. // A sample service with a single message. Note that this message's error type
  11. // will be a _wrapped_ union.
  12. const service = avro.Service.forProtocol(avro.readProtocol(`
  13. protocol EchoService {
  14. error SomeError { string details; }
  15. error AnotherError { int code = -1; }
  16. string upperCase(string str) throws SomeError, AnotherError;
  17. }
  18. `), {wrapUnions: true});
  19.  
  20. // Extract our custom errors' constructors to instantiate them idiomatically.
  21. const SomeError = service.type('SomeError').recordConstructor;
  22. const AnotherError = service.type('AnotherError').recordConstructor;
  23.  
  24. // A server for our service which accepts promise-based handlers.
  25. const server = promisify.promisifyServer(service.createServer({silent: true}))
  26. .onUpperCase(function (str) {
  27. // OK case, we just return a value (if this computation was asynchronous,
  28. // we would just return a promise instead).
  29. return str.toUpperCase();
  30.  
  31. // All the following lines are valid exception flows!
  32. //
  33. // Throwing a custom error (without having to wrap it):
  34. // throw new SomeError('bar');
  35. // throw new AnotherError();
  36. //
  37. // Throwing a "system error" (either as an error, or using the strictly
  38. // correct Avro type):
  39. // throw new Error('foo');
  40. // throw {string: 'baz'};
  41. });
  42.  
  43.  
  44. // Promise-based client.
  45. const client = promisify.promisifyClient(service.createClient({server}));
  46.  
  47. client.upperCase('abc')
  48. // OK case, the response is returned as expect.
  49. .then(console.log)
  50. // If a custom error is returned, it will be always unwrapped; this enables
  51. // dispatching on the error's type:
  52. .catch(SomeError, function (err) {
  53. console.error(`got some error with details ${err.details}`);
  54. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement