1 2
import { create as createLogger } from '../common/log'
2
import { Middleware, MiddlewareCallback, MiddlewareServices, Pipelines } from '../types/middleware'
3 2
import * as IlpPacket from 'ilp-packet'
4

5 2
export default class ErrorHandlerMiddleware implements Middleware {
6
  private getOwnAddress: () => string
7

8
  constructor (opts: {}, api: MiddlewareServices) {
9 2
    this.getOwnAddress = api.getOwnAddress
10
  }
11

12
  async applyToPipelines (pipelines: Pipelines, accountId: string) {
13 2
    const log = createLogger(`error-handler-middleware[${accountId}]`)
14

15
    /**
16
     * Important middleware. It ensures any errors thrown through the middleware pipe is converted to correct ILP
17
     * reject that is sent back to sender.
18
     */
19 2
    pipelines.incomingData.insertLast({
20
      name: 'errorHandler',
21
      method: async (data: Buffer, next: MiddlewareCallback<Buffer, Buffer>) => {
22 2
        try {
23 2
          const response = await next(data)
24

25 2
          if (!Buffer.isBuffer(response)) {
26 0
            throw new Error('handler did not return a value.')
27
          }
28

29 2
          return response
30
        } catch (e) {
31 2
          let err = e
32 2
          if (!err || typeof err !== 'object') {
33 0
            err = new Error('Non-object thrown: ' + e)
34
          }
35

36 2
          log.debug('error in data handler, creating rejection. ilpErrorCode=%s error=%s', err.ilpErrorCode, err.stack ? err.stack : err)
37

38 2
          return IlpPacket.errorToReject(this.getOwnAddress(), err)
39
        }
40
      }
41
    })
42

43 2
    pipelines.incomingMoney.insertLast({
44
      name: 'errorHandler',
45
      method: async (amount: string, next: MiddlewareCallback<string, void>) => {
46 0
        try {
47 0
          return await next(amount)
48
        } catch (e) {
49 0
          let err = e
50 2
          if (!err || typeof err !== 'object') {
51 0
            err = new Error('non-object thrown. value=' + e)
52
          }
53

54 2
          log.debug('error in money handler. error=%s', err.stack ? err.stack : err)
55

56 0
          throw err
57
        }
58
      }
59
    })
60
  }
61
}

Read our documentation on viewing source code .

Loading