Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* jshint esversion: 6, node: true */
- 'use strict';
- /** Sample code using the promisified service API. */
- const avro = require('avsc');
- const promisify = require('./promisify');
- // A sample service with a single message. Note that this message's error type
- // will be a _wrapped_ union.
- const service = avro.Service.forProtocol(avro.readProtocol(`
- protocol EchoService {
- error SomeError { string details; }
- error AnotherError { int code = -1; }
- string upperCase(string str) throws SomeError, AnotherError;
- }
- `), {wrapUnions: true});
- // Extract our custom errors' constructors to instantiate them idiomatically.
- const SomeError = service.type('SomeError').recordConstructor;
- const AnotherError = service.type('AnotherError').recordConstructor;
- // A server for our service which accepts promise-based handlers.
- const server = promisify.promisifyServer(service.createServer({silent: true}))
- .onUpperCase(function (str) {
- // OK case, we just return a value (if this computation was asynchronous,
- // we would just return a promise instead).
- return str.toUpperCase();
- // All the following lines are valid exception flows!
- //
- // Throwing a custom error (without having to wrap it):
- // throw new SomeError('bar');
- // throw new AnotherError();
- //
- // Throwing a "system error" (either as an error, or using the strictly
- // correct Avro type):
- // throw new Error('foo');
- // throw {string: 'baz'};
- });
- // Promise-based client.
- const client = promisify.promisifyClient(service.createClient({server}));
- client.upperCase('abc')
- // OK case, the response is returned as expect.
- .then(console.log)
- // If a custom error is returned, it will be always unwrapped; this enables
- // dispatching on the error's type:
- .catch(SomeError, function (err) {
- console.error(`got some error with details ${err.details}`);
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement