weixin_39729784
weixin_39729784
2020-12-08 22:10

How to catch exceptions?

Looks like exception catches in getAccount and just log it inside. How to catch it myself? And note last lines in output.

js
const ax = require('axios')
const BnbApiClient = require('-chain/javascript-sdk');

const l = x => console.log(JSON.stringify(x, null, 2))

const ad = 'tbnb1vme7c3kq4njqdmcr4dchd0xvy72wj0aqkjzhfs'
const pk = '1a16367e435c0fc02a4e940e1a5e3b1288c0101b85ef5872bcb7b9de840238e2'

;(async() => {
  try {
    // const{data} = await ax('https://testnet-dex.binance.org/')
    // l(data)
    // return

    l(1)
    const bnbClient = new BnbApiClient('https://testnet-dex.binance.org/');

    l(2)

    // await bnbClient.setPrivateKey(pk)
    bnbClient.chooseNetwork("testnet"); // or this can be "mainnet"
    bnbClient.initChain();

    const addr = bnbClient.getAccount(ad);
    l({addr})

    // const a = bnbClient.createAccountWithKeystore('pass');
    // l(a)

  } catch(e) {
    console.log(111, e.request)
  }
})()

Outputs:

log
1
2
error in HttpRequest#request { Error: Request failed with status code 404
    at createError (/root/projects/test/node_modules/-chain/javascript-sdk/node_modules/axios/lib/core/createError.js:16:15)
    at settle (/root/projects/test/node_modules/-chain/javascript-sdk/node_modules/axios/lib/core/settle.js:17:12)
    at IncomingMessage.handleStreamEnd (/root/projects/test/node_modules/-chain/javascript-sdk/node_modules/axios/lib/adapters/http.js:237:11)
    at IncomingMessage.emit (events.js:198:15)
    at endReadableNT (_stream_readable.js:1139:12)
    at processTicksAndRejections (internal/process/task_queues.js:81:17)
  config:
   { url:
      'https://testnet-dex.binance.org/api/v1/account/tbnb1vme7c3kq4njqdmcr4dchd0xvy72wj0aqkjzhfs',
     method: 'get',
     headers:
      { Accept: 'application/json, text/plain, */*',
        'User-Agent': 'axios/0.19.0' },
     baseURL: 'https://testnet-dex.binance.org/',
     transformRequest: [ [Function: transformRequest] ],
     transformResponse: [ [Function: transformResponse] ],
     timeout: 0,
     adapter: [Function: httpAdapter],
     xsrfCookieName: 'XSRF-TOKEN',
     xsrfHeaderName: 'X-XSRF-TOKEN',
     maxContentLength: -1,
     validateStatus: [Function: validateStatus],
     data: undefined },
  request:
   ClientRequest {
     _events:
      [Object: null prototype] {
        socket: [Function],
        abort: [Function],
        aborted: [Function],
        error: [Function],
        timeout: [Function],
        prefinish: [Function: requestOnPrefinish] },
     _eventsCount: 6,
     _maxListeners: undefined,
     outputData: [],
     outputSize: 0,
     writable: true,
     _last: true,
     chunkedEncoding: false,
     shouldKeepAlive: false,
     useChunkedEncodingByDefault: false,
     sendDate: false,
     _removedConnection: false,
     _removedContLen: false,
     _removedTE: false,
     _contentLength: 0,
     _hasBody: true,
     _trailer: '',
     finished: true,
     _headerSent: true,
     socket:
      TLSSocket {
        _tlsOptions: [Object],
        _secureEstablished: true,
        _securePending: false,
        _newSessionPending: false,
        _controlReleased: true,
        _SNICallback: null,
        servername: 'testnet-dex.binance.org',
        alpnProtocol: false,
        authorized: true,
        authorizationError: null,
        encrypted: true,
        _events: [Object],
        _eventsCount: 9,
        connecting: false,
        _hadError: false,
        _parent: null,
        _host: 'testnet-dex.binance.org',
        _readableState: [ReadableState],
        readable: true,
        _maxListeners: undefined,
        _writableState: [WritableState],
        writable: false,
        allowHalfOpen: false,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: undefined,
        _server: null,
        ssl: [TLSWrap],
        _requestCert: true,
        _rejectUnauthorized: true,
        parser: null,
        _httpMessage: [Circular],
        [Symbol(res)]: [TLSWrap],
        [Symbol(asyncId)]: 28,
        [Symbol(kHandle)]: [TLSWrap],
        [Symbol(lastWriteQueueSize)]: 0,
        [Symbol(timeout)]: null,
        [Symbol(kBytesRead)]: 0,
        [Symbol(kBytesWritten)]: 0,
        [Symbol(connect-options)]: [Object] },
     connection:
      TLSSocket {
        _tlsOptions: [Object],
        _secureEstablished: true,
        _securePending: false,
        _newSessionPending: false,
        _controlReleased: true,
        _SNICallback: null,
        servername: 'testnet-dex.binance.org',
        alpnProtocol: false,
        authorized: true,
        authorizationError: null,
        encrypted: true,
        _events: [Object],
        _eventsCount: 9,
        connecting: false,
        _hadError: false,
        _parent: null,
        _host: 'testnet-dex.binance.org',
        _readableState: [ReadableState],
        readable: true,
        _maxListeners: undefined,
        _writableState: [WritableState],
        writable: false,
        allowHalfOpen: false,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: undefined,
        _server: null,
        ssl: [TLSWrap],
        _requestCert: true,
        _rejectUnauthorized: true,
        parser: null,
        _httpMessage: [Circular],
        [Symbol(res)]: [TLSWrap],
        [Symbol(asyncId)]: 28,
        [Symbol(kHandle)]: [TLSWrap],
        [Symbol(lastWriteQueueSize)]: 0,
        [Symbol(timeout)]: null,
        [Symbol(kBytesRead)]: 0,
        [Symbol(kBytesWritten)]: 0,
        [Symbol(connect-options)]: [Object] },
     _header:
      'GET /api/v1/account/tbnb1vme7c3kq4njqdmcr4dchd0xvy72wj0aqkjzhfs HTTP/1.1\r\nAccept: application/json, text/plain, */*\r\nUser-Agent: axios/0.19.0\r\nHost: testnet-dex.binance.org\r\nConnection: close\r\n\r\n',
     _onPendingData: [Function: noopPendingOutput],
     agent:
      Agent {
        _events: [Object],
        _eventsCount: 1,
        _maxListeners: undefined,
        defaultPort: 443,
        protocol: 'https:',
        options: [Object],
        requests: {},
        sockets: [Object],
        freeSockets: {},
        keepAliveMsecs: 1000,
        keepAlive: false,
        maxSockets: Infinity,
        maxFreeSockets: 256,
        maxCachedSessions: 100,
        _sessionCache: [Object] },
     socketPath: undefined,
     timeout: undefined,
     method: 'GET',
     path:
      '/api/v1/account/tbnb1vme7c3kq4njqdmcr4dchd0xvy72wj0aqkjzhfs',
     _ended: true,
     res:
      IncomingMessage {
        _readableState: [ReadableState],
        readable: false,
        _events: [Object],
        _eventsCount: 3,
        _maxListeners: undefined,
        socket: [TLSSocket],
        connection: [TLSSocket],
        httpVersionMajor: 1,
        httpVersionMinor: 1,
        httpVersion: '1.1',
        complete: true,
        headers: [Object],
        rawHeaders: [Array],
        trailers: {},
        rawTrailers: [],
        aborted: false,
        upgrade: false,
        url: '',
        method: null,
        statusCode: 404,
        statusMessage: 'Not Found',
        client: [TLSSocket],
        _consuming: false,
        _dumped: false,
        req: [Circular],
        responseUrl:
         'https://testnet-dex.binance.org/api/v1/account/tbnb1vme7c3kq4njqdmcr4dchd0xvy72wj0aqkjzhfs',
        redirects: [] },
     aborted: false,
     timeoutCb: null,
     upgradeOrConnect: false,
     parser: null,
     maxHeadersCount: null,
     _redirectable:
      Writable {
        _writableState: [WritableState],
        writable: true,
        _events: [Object],
        _eventsCount: 2,
        _maxListeners: undefined,
        _options: [Object],
        _redirectCount: 0,
        _redirects: [],
        _requestBodyLength: 0,
        _requestBodyBuffers: [],
        _onNativeResponse: [Function],
        _currentRequest: [Circular],
        _currentUrl:
         'https://testnet-dex.binance.org/api/v1/account/tbnb1vme7c3kq4njqdmcr4dchd0xvy72wj0aqkjzhfs' },
     [Symbol(isCorked)]: false,
     [Symbol(outHeadersKey)]:
      [Object: null prototype] { accept: [Array], 'user-agent': [Array], host: [Array] } },
  response:
   { status: 404,
     statusText: 'Not Found',
     headers:
      { 'content-type': 'application/json',
        'content-length': '0',
        connection: 'close',
        date: 'Wed, 12 Jun 2019 05:16:09 GMT',
        'x-ratelimit-limit-second': '5',
        'x-ratelimit-remaining-second': '4',
        'x-ratelimit-limit-minute': '300',
        'x-ratelimit-remaining-minute': '299',
        'access-control-allow-origin': '*',
        'cache-control': 'no-cache, no-store, must-revalidate',
        'strict-transport-security': 'max-age=31536000',
        'x-kong-upstream-latency': '2',
        'x-kong-proxy-latency': '0',
        via:
         'kong/0.14.1, 1.1 5f77bd93eaeac8e32d1c411a80449035.cloudfront.net (CloudFront)',
        'x-frame-options': 'SAMEORIGIN',
        'x-xss-protection': '1; mode=block',
        'x-content-type-options': 'nosniff',
        'referrer-policy': 'origin-when-cross-origin',
        'x-cache': 'Error from cloudfront',
        'x-amz-cf-id': 'GfkponeFETaeg1CTzj8Mx9aqRw5h6bLIJ9rbOdeTn7DxvOiGMW9xYQ==' },
     config:
      { url:
         'https://testnet-dex.binance.org/api/v1/account/tbnb1vme7c3kq4njqdmcr4dchd0xvy72wj0aqkjzhfs',
        method: 'get',
        headers: [Object],
        baseURL: 'https://testnet-dex.binance.org/',
        transformRequest: [Array],
        transformResponse: [Array],
        timeout: 0,
        adapter: [Function: httpAdapter],
        xsrfCookieName: 'XSRF-TOKEN',
        xsrfHeaderName: 'X-XSRF-TOKEN',
        maxContentLength: -1,
        validateStatus: [Function: validateStatus],
        data: undefined },
     request:
      ClientRequest {
        _events: [Object],
        _eventsCount: 6,
        _maxListeners: undefined,
        outputData: [],
        outputSize: 0,
        writable: true,
        _last: true,
        chunkedEncoding: false,
        shouldKeepAlive: false,
        useChunkedEncodingByDefault: false,
        sendDate: false,
        _removedConnection: false,
        _removedContLen: false,
        _removedTE: false,
        _contentLength: 0,
        _hasBody: true,
        _trailer: '',
        finished: true,
        _headerSent: true,
        socket: [TLSSocket],
        connection: [TLSSocket],
        _header:
         'GET /api/v1/account/tbnb1vme7c3kq4njqdmcr4dchd0xvy72wj0aqkjzhfs HTTP/1.1\r\nAccept: application/json, text/plain, */*\r\nUser-Agent: axios/0.19.0\r\nHost: testnet-dex.binance.org\r\nConnection: close\r\n\r\n',
        _onPendingData: [Function: noopPendingOutput],
        agent: [Agent],
        socketPath: undefined,
        timeout: undefined,
        method: 'GET',
        path:
         '/api/v1/account/tbnb1vme7c3kq4njqdmcr4dchd0xvy72wj0aqkjzhfs',
        _ended: true,
        res: [IncomingMessage],
        aborted: false,
        timeoutCb: null,
        upgradeOrConnect: false,
        parser: null,
        maxHeadersCount: null,
        _redirectable: [Writable],
        [Symbol(isCorked)]: false,
        [Symbol(outHeadersKey)]: [Object] },
     data: '' },
  isAxiosError: true,
  toJSON: [Function] } undefined
{
  "addr": null
}

该提问来源于开源项目:binance-chain/javascript-sdk

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

4条回答

  • weixin_39796533 weixin_39796533 5月前

    Thanks for the report. This seems to be caused by this code not bubbling up the error. For now this also seems to be the case with RPC calls.

    We will take care of this next week or feel free to open a PR!

    点赞 评论 复制链接分享
  • weixin_39862484 weixin_39862484 5月前

    This issue is not just related to getAccount but potentially to many other methods, such as placeOrder in my case.

    点赞 评论 复制链接分享
  • weixin_39856607 weixin_39856607 5月前

    Any update on this? It is very frustrating not to be able to catch those errors properly since they spam the logs really badly.

    点赞 评论 复制链接分享
  • weixin_39550258 weixin_39550258 5月前

    try latest version

    点赞 评论 复制链接分享

相关推荐