vanita5 / mastodon-api

Mastodon API Client Library
MIT License
122 stars 21 forks source link

Actually catch/surface transport-level errors #19

Open BooDoo opened 3 years ago

BooDoo commented 3 years ago

Setting .on('error') listener within .on('respone') block lead to unhandled exceptions from underlying Request events for e.g. CERT_HAS_EXPIRED.

Breaking this out so listener attaches appropriately and errors are caught/surfaced as intended. Misbehavior discovered and submitted fix tested in production backend of cheapbotstootsweet.com.

Sample call:

async function sendToot(params, M) {
  let {data, resp} = await M.post('/statuses', params).catch((err)=>console.error(err));
  return data;
}

async function runTest() {
  let tootData = await sendToot({status: "testing", visibility: "public"}, new Mastodon(CREDENTIALS));
  console.log("We made it past the error!");
}

runTest();

Behavior before PR:

 throw er; // Unhandled 'error' event
      ^

Error: certificate has expired
    at TLSSocket.onConnectSecure (node:_tls_wrap:1498:34)
    at TLSSocket.emit (node:events:376:20)
    at TLSSocket._finishInit (node:_tls_wrap:933:8)
    at TLSWrap.ssl.onhandshakedone (node:_tls_wrap:707:12)
Emitted 'error' event on Request instance at:
    at Request.onRequestError (/opt/cbts/prod/traceryhosting-backend/node_modules/request/request.js:881:8)
    at ClientRequest.emit (node:events:376:20)
    at TLSSocket.socketErrorListener (node:_http_client:490:9)
    at TLSSocket.emit (node:events:376:20)
    at emitErrorNT (node:internal/streams/destroy:188:8)
    at emitErrorCloseNT (node:internal/streams/destroy:153:3)
    at processTicksAndRejections (node:internal/process/task_queues:80:21) {
  code: 'CERT_HAS_EXPIRED'
}

Behavior after PR:

Error: certificate has expired
    at TLSSocket.onConnectSecure (node:_tls_wrap:1498:34)
    at TLSSocket.emit (node:events:376:20)
    at TLSSocket._finishInit (node:_tls_wrap:933:8)
    at TLSWrap.ssl.onhandshakedone (node:_tls_wrap:707:12) {
  code: 'CERT_HAS_EXPIRED',
  allErrors: [],
  mastodonReply: ''
}
We made it past the error!