From e0cd77359bf3127751796ca6ff55e94dc5d0582f Mon Sep 17 00:00:00 2001 From: Mike Date: Mon, 8 Jul 2024 20:42:33 -0400 Subject: [PATCH] fix: application crash when timeout encountered (#569) I encountered occasional application crashes and traced them back to timeouts coming from the Nylas API. After reviewing the Nylas-SDK, I found the culprit in the `setTimeout` call used to abort the request. It's bad practice to throw an error from `setTimeout` as its `try...catch` blocks will not intercept the error. Instead, these errors will crash the application. `node-fetch` will reject when `controller.abort()` is called, so we don't need to throw from the timeout anyway. Reference: https://jaketrent.com/post/catch-error-thrown-settimeout/ https://nodejs.org/dist/latest-v7.x/docs/api/errors.html#errors_node_js_style_callbacks --- src/apiClient.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/apiClient.ts b/src/apiClient.ts index 40113d10..744d7626 100644 --- a/src/apiClient.ts +++ b/src/apiClient.ts @@ -148,7 +148,6 @@ export default class APIClient { const controller: AbortController = new AbortController(); const timeout = setTimeout(() => { controller.abort(); - throw new NylasSdkTimeoutError(req.url, this.timeout); }, this.timeout); try { @@ -187,6 +186,10 @@ export default class APIClient { return response; } catch (error) { + if (error instanceof Error && error.name === 'AbortError') { + throw new NylasSdkTimeoutError(req.url, this.timeout); + } + clearTimeout(timeout); throw error; }