浏览代码

fix(api-gateway): retry attempts and logs

Karol Sójko 1 年之前
父节点
当前提交
654663d17f
共有 1 个文件被更改,包括 15 次插入7 次删除
  1. 15 7
      packages/api-gateway/src/Service/Http/HttpServiceProxy.ts

+ 15 - 7
packages/api-gateway/src/Service/Http/HttpServiceProxy.ts

@@ -240,10 +240,9 @@ export class HttpServiceProxy implements ServiceProxyInterface {
 
       return serviceResponse
     } catch (error) {
-      const requestTimedOut =
-        'code' in (error as Record<string, unknown>) && (error as Record<string, unknown>).code === 'ETIMEDOUT'
+      const requestDidNotMakeIt = this.requestTimedOutOrDidNotReachDestination(error as Record<string, unknown>)
       const tooManyRetryAttempts = retryAttempt && retryAttempt > 2
-      if (!tooManyRetryAttempts && requestTimedOut) {
+      if (!tooManyRetryAttempts && requestDidNotMakeIt) {
         await this.timer.sleep(50)
 
         const nextRetryAttempt = retryAttempt ? retryAttempt + 1 : 1
@@ -267,12 +266,12 @@ export class HttpServiceProxy implements ServiceProxyInterface {
         : (error as Error).message
 
       this.logger.error(
-        `Could not pass the request to ${serverUrl}/${endpointOrMethodIdentifier} on underlying service: ${JSON.stringify(
-          error,
-        )}`,
+        tooManyRetryAttempts
+          ? `Request to ${serverUrl}/${endpointOrMethodIdentifier} timed out after ${retryAttempt} retries`
+          : `Could not pass the request to ${serverUrl}/${endpointOrMethodIdentifier} on underlying service: ${errorMessage}`,
       )
 
-      this.logger.debug('Response error: %O', (error as AxiosError).response ?? error)
+      this.logger.debug(`Response error: ${JSON.stringify(error)}`)
 
       if ((error as AxiosError).response?.headers['content-type']) {
         response.setHeader('content-type', (error as AxiosError).response?.headers['content-type'] as string)
@@ -414,4 +413,13 @@ export class HttpServiceProxy implements ServiceProxyInterface {
       }
     })
   }
+
+  private requestTimedOutOrDidNotReachDestination(error: Record<string, unknown>): boolean {
+    return (
+      ('code' in error && error.code === 'ETIMEDOUT') ||
+      ('response' in error &&
+        'status' in (error.response as Record<string, unknown>) &&
+        [503, 504].includes((error.response as Record<string, unknown>).status as number))
+    )
+  }
 }