Skip to content

Commit 04446d4

Browse files
authoredDec 14, 2020
fix(message-handler): Rewire promise rejections as Error objects (#300)
fixes #294
1 parent 07fcb76 commit 04446d4

File tree

16 files changed

+92
-36
lines changed

16 files changed

+92
-36
lines changed
 

‎package.json

+4-3
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,10 @@
88
"test:integration-build": "yarn test:integration-prepare && yarn test:integration-pretty",
99
"test:integration-prepare": "ts-node --project packages/tsconfig.settings.json ./scripts/prepare-integration-tests.ts",
1010
"test:integration-pretty":"prettier --write __tests__/shared/documentationExamples.ts",
11-
"test:integration": "yarn test:integration-build && yarn test",
12-
"test": "jest --config=jest.json --maxWorkers=2",
13-
"test:watch": "jest --config=jest.json --watch --verbose --coverage=false",
11+
"test:integration": "yarn test:integration-build && yarn test:ci",
12+
"test:ci": "jest --config=jest.json --maxWorkers=2",
13+
"test": "jest --config=jest.json --coverage=false",
14+
"test:watch": "yarn test --watch --verbose",
1415
"daf": "./packages/daf-cli/bin/daf.js",
1516
"prettier": "prettier --write '{packages,__tests__, !build}/**/*.ts'",
1617
"build-clean": "rimraf ./packages/*/build ./packages/*/node_modules ./packages/*/tsconfig.tsbuildinfo && jest --clearCache",

‎packages/daf-core/api/daf-core.api.md

+6
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,12 @@ export class Agent implements IAgent {
1616
readonly methods: IPluginMethodMap;
1717
}
1818

19+
// @public
20+
export const CoreEvents: {
21+
error: string;
22+
warning: string;
23+
};
24+
1925
// @public
2026
export function createAgent<T extends IPluginMethodMap>(options: IAgentOptions): TAgent<T>;
2127

‎packages/daf-core/src/__tests__/agent.subscriber.test.ts

+6-5
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { Agent } from '../agent'
2+
import { CoreEvents } from '../coreEvents'
23
import { IEventListener } from '../types/IAgent'
34

45
function sleep(ms: number) {
@@ -77,7 +78,7 @@ describe('daf-core agent', () => {
7778
},
7879
}
7980
const errorHandler: IEventListener = {
80-
eventTypes: ['error'],
81+
eventTypes: [CoreEvents.error],
8182
onEvent: jest.fn(),
8283
}
8384
const agent = new Agent({
@@ -88,7 +89,7 @@ describe('daf-core agent', () => {
8889

8990
expect(errorHandler.onEvent).toBeCalledWith(
9091
{
91-
type: 'error',
92+
type: CoreEvents.error,
9293
data: new Error("I can't handle it!!!!"),
9394
},
9495
{ agent: agent },
@@ -105,9 +106,9 @@ describe('daf-core agent', () => {
105106
},
106107
}
107108
const errorHandler: IEventListener = {
108-
eventTypes: ['error'],
109+
eventTypes: [CoreEvents.error],
109110
onEvent: async ({ type, data }, context) => {
110-
expect(type).toBe('error')
111+
expect(type).toBe(CoreEvents.error)
111112
const err = data as Error
112113
expect(err.message).toMatch("I can't handle it after waiting so long!!!!")
113114
},
@@ -176,7 +177,7 @@ describe('daf-core agent', () => {
176177
},
177178
}
178179
const errorHandler: IEventListener = {
179-
eventTypes: ['error'],
180+
eventTypes: [CoreEvents.error],
180181
onEvent: async () => {
181182
throw new Error('barError')
182183
},

‎packages/daf-core/src/agent.ts

+5-4
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { validateArguments, validateReturnType } from './validator'
33
import ValidationErrorSchema from './schemas/ValidationError'
44
import Debug from 'debug'
55
import { EventEmitter } from 'events'
6+
import { CoreEvents } from './coreEvents'
67

78
/**
89
* Filters unauthorized methods. By default all methods are authorized
@@ -146,8 +147,8 @@ export class Agent implements IAgent {
146147
)
147148
this.eventQueue.push(promise)
148149
promise?.catch((rejection) => {
149-
if (eventType !== 'error') {
150-
this.eventBus.emit('error', rejection)
150+
if (eventType !== CoreEvents.error) {
151+
this.eventBus.emit(CoreEvents.error, rejection)
151152
} else {
152153
this.eventQueue.push(
153154
Promise.reject(
@@ -254,10 +255,10 @@ export class Agent implements IAgent {
254255
* Ex: `await agent.emit('foo', {eventData})`
255256
*
256257
* In case an error is thrown while processing an event, the error is re-emitted as an event
257-
* of type `error` with a `EventListenerError` as payload.
258+
* of type `CoreEvents.error` with a `EventListenerError` as payload.
258259
*
259260
* Note that `await agent.emit()` will NOT throw an error. To process errors, use a listener
260-
* with `eventTypes: ["error"]` in the definition.
261+
* with `eventTypes: [ CoreEvents.error ]` in the definition.
261262
*
262263
* @param eventType - the type of event being emitted
263264
* @param data - event payload.

‎packages/daf-core/src/coreEvents.ts

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* This collection defines the core event types.
3+
*
4+
* @public
5+
*/
6+
export const CoreEvents = {
7+
/**
8+
* This event type is used to signal an error to event listeners.
9+
*
10+
* @public
11+
*/
12+
error: 'ev_err',
13+
14+
/**
15+
* This event type is used to signal a warning to event listeners.
16+
*
17+
* @public
18+
*/
19+
warning: 'ev_warn',
20+
}

‎packages/daf-core/src/index.ts

+1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
*/
66
export { Agent, createAgent, IAgentOptions } from './agent'
77
export { ValidationError } from './validator'
8+
export { CoreEvents } from './coreEvents'
89
export * from './types/IAgent'
910
export * from './types/IDataStore'
1011
export * from './types/IIdentity'

‎packages/daf-did-comm/src/action-handler.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -126,13 +126,13 @@ export class DIDComm implements IAgentPlugin {
126126
})
127127
}
128128

129-
return Promise.reject('Message not sent')
129+
return Promise.reject(new Error('Message not sent'))
130130
} catch (e) {
131131
return Promise.reject(e)
132132
}
133133
} else {
134134
debug('No Messaging service in didDoc')
135-
return Promise.reject('No service endpoint')
135+
return Promise.reject(new Error('No service endpoint'))
136136
}
137137
}
138138
}

‎packages/daf-did-jwt/src/__tests__/message-handler.test.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -87,12 +87,12 @@ describe('daf-did-jwt', () => {
8787
it('should reject unknown message type', async () => {
8888
const mockNextHandler = {
8989
setNext: jest.fn(),
90-
handle: jest.fn().mockRejectedValue('Unsupported message type'),
90+
handle: jest.fn().mockRejectedValue(new Error('Unsupported message type')),
9191
}
9292
const handler = new JwtMessageHandler()
9393
handler.setNext(mockNextHandler)
9494
const message = new Message({ raw: 'test', metaData: [{ type: 'test' }] })
95-
expect(handler.handle(message, context)).rejects.toEqual('Unsupported message type')
95+
await expect(handler.handle(message, context)).rejects.toThrow('Unsupported message type')
9696
})
9797

9898
it('should set data field for VC jwt', async () => {

‎packages/daf-elem-did/src/identity-provider.ts

+4-4
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ export class ElemIdentityProvider extends AbstractIdentityProvider {
5656
})
5757

5858
if (response.status !== 200) {
59-
return Promise.reject(response.statusText)
59+
return Promise.reject(new Error(response.statusText))
6060
}
6161

6262
const identity: Omit<IIdentity, 'provider'> = {
@@ -82,7 +82,7 @@ export class ElemIdentityProvider extends AbstractIdentityProvider {
8282
context: IContext,
8383
): Promise<any> {
8484
if (!identity.controllerKeyId) throw Error('ControllerKeyId does not exist')
85-
85+
8686
const primaryKey = await await context.agent.keyManagerGetKey({ kid: identity.controllerKeyId })
8787

8888
debug('Fetching list of previous operations')
@@ -91,7 +91,7 @@ export class ElemIdentityProvider extends AbstractIdentityProvider {
9191

9292
debug('Operations count:', operations.length)
9393
if (operations.length === 0) {
94-
return Promise.reject('There should be at least one operation')
94+
return Promise.reject(new Error('There should be at least one operation'))
9595
}
9696

9797
const lastOperation = operations.pop()
@@ -120,7 +120,7 @@ export class ElemIdentityProvider extends AbstractIdentityProvider {
120120

121121
if (response2.status !== 200) {
122122
debug(response2.statusText)
123-
return Promise.reject(response2.statusText)
123+
return Promise.reject(new Error(response2.statusText))
124124
}
125125

126126
debug('Success. New publicKey:', key.publicKeyHex)
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,34 @@
1+
import { createAgent, IAgentContext, IMessageHandler } from 'daf-core/src'
2+
import { MessageHandler } from '..'
3+
import { AbstractMessageHandler, Message } from '../../build'
4+
5+
jest.setTimeout(30000)
6+
7+
class DummyHandler extends AbstractMessageHandler {
8+
async handle(message: Message, context: IAgentContext<{}>): Promise<Message> {
9+
return super.handle(message, context)
10+
}
11+
}
12+
113
describe('daf-message-handler', () => {
214
const a = 100
315
it('should run a dummy test', () => {
416
expect(a).toEqual(100)
517
})
18+
19+
let agent = createAgent<IMessageHandler>({
20+
plugins: [
21+
new MessageHandler({
22+
messageHandlers: [new DummyHandler()],
23+
}),
24+
],
25+
})
26+
27+
it('should reject unknown message', async () => {
28+
expect.assertions(1)
29+
const raw = 'some message of unknown format'
30+
await expect(agent.handleMessage({ raw, save: false, metaData: [{ type: 'test' }] })).rejects.toThrow(
31+
'Unsupported message type',
32+
)
33+
})
634
})

‎packages/daf-message-handler/src/abstract-message-handler.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { IAgentContext } from 'daf-core'
22
import { Message } from './message'
33

4-
export const unsupportedMessageTypeError = 'Unsupported message type'
4+
export const unsupportedMessageTypeError = new Error('Unsupported message type')
55

66
/**
77
* An abstract class for creating {@link daf-message-handler#MessageHandler} plugins

‎packages/daf-message-handler/src/message-handler.ts

+3-2
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
IMessageHandler,
66
IHandleMessageArgs,
77
schema,
8+
CoreEvents,
89
} from 'daf-core'
910
import { Message } from './message'
1011
import { AbstractMessageHandler } from './abstract-message-handler'
@@ -15,7 +16,7 @@ const debug = Debug('daf:message-handler')
1516
export const EventTypes = {
1617
validatedMessage: 'validatedMessage',
1718
savedMessage: 'savedMessage',
18-
error: 'error',
19+
error: CoreEvents.error,
1920
}
2021

2122
/**
@@ -54,7 +55,7 @@ export class MessageHandler implements IAgentPlugin {
5455
const { raw, metaData, save } = args
5556
debug('%o', { raw, metaData, save })
5657
if (!this.messageHandler) {
57-
return Promise.reject('Message handler not provided')
58+
return Promise.reject(new Error('Message handler not provided'))
5859
}
5960

6061
try {

‎packages/daf-resolver/src/universal-resolver.ts

+4-4
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,10 @@ export class UniversalResolver {
1616
const ddo = await result.json()
1717
return ddo.didDocument
1818
} catch (e) {
19-
return Promise.reject(e.message)
19+
return Promise.reject(e)
2020
}
21-
}
22-
21+
}
22+
2323
return resolve
2424
}
25-
}
25+
}

‎packages/daf-typeorm/api/daf-typeorm.api.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ export class DataStoreORM implements IAgentPlugin {
135135
}
136136

137137
// @public (undocumented)
138-
export const Entities: (typeof Credential_2 | typeof Identity | typeof Claim | typeof Presentation | typeof Message | typeof Key | typeof Service)[];
138+
export const Entities: (typeof Identity | typeof Message | typeof Claim | typeof Credential_2 | typeof Presentation | typeof Key | typeof Service)[];
139139

140140
// @public (undocumented)
141141
export interface FindArgs<TColumns> {

‎packages/daf-url/src/__tests__/message-handler.test.ts

+4-7
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ describe('daf-url', () => {
1818

1919
it('should reject unknown message type', async () => {
2020
const message = new Message({ raw: 'test', metaData: [{ type: 'test' }] })
21-
expect(messageHandler.handle(message, context)).rejects.toEqual('Unsupported message type')
21+
await expect(messageHandler.handle(message, context)).rejects.toThrow('Unsupported message type')
2222
})
2323

2424
it('should transform message after standard URL', async () => {
@@ -32,19 +32,16 @@ describe('daf-url', () => {
3232
},
3333
],
3434
})
35-
expect(messageHandler.handle(message, context)).rejects.toEqual('Unsupported message type')
35+
await expect(messageHandler.handle(message, context)).rejects.toThrow('Unsupported message type')
3636
expect(message.raw).toEqual(JWT)
3737
})
3838

3939
it('should try to load data from URL if URL is not standard', async () => {
4040
const message = new Message({ raw: 'https://example.com/public-profile.jwt' })
4141
fetchMock.mockResponse('mockbody')
4242
expect.assertions(2)
43-
try {
44-
await messageHandler.handle(message, context)
45-
} catch (e) {
46-
expect(e).toMatch('Unsupported message type')
47-
}
43+
44+
await expect(messageHandler.handle(message, context)).rejects.toThrow('Unsupported message type')
4845

4946
expect(message.raw).toEqual('mockbody')
5047
})

‎packages/daf-w3c/src/__tests__/message-handler.test.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ describe('daf-w3c', () => {
9090

9191
it('should reject unknown message type', async () => {
9292
const message = new Message({ raw: 'test', metaData: [{ type: 'test' }] })
93-
expect(handler.handle(message, context)).rejects.toEqual('Unsupported message type')
93+
await expect(handler.handle(message, context)).rejects.toThrow('Unsupported message type')
9494
})
9595

9696
it('should return handled VC message', async () => {

0 commit comments

Comments
 (0)
Please sign in to comment.