All files / src/errors apiErrors.ts

100% Statements 19/19
100% Branches 0/0
100% Functions 7/7
100% Lines 19/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77  8x   8x     53x     53x 53x       8x                           43x 43x 43x 43x 43x       2x       6x       25x             8x           10x     10x 10x       4x                      
import { ErrorPlainResponse, ErrorResponse } from '../types'
import { getRetryAfter } from './getRetryAfter'
 
export class SdkError extends Error {
  constructor(
    message: string,
    readonly response?: Response,
    cause?: Error
  ) {
    super(message, { cause })
    this.name = this.constructor.name
  }
}
 
export class RequestError<Code extends number = number, Body = unknown> extends SdkError {
  // HTTP Status code
  readonly statusCode: Code
 
  // API error code
  readonly errorCode: string
 
  // API error response
  readonly responseBody: Body
 
  // Raw HTTP response
  override readonly response: Response
 
  constructor(message: string, body: Body, statusCode: Code, errorCode: string, response: Response) {
    super(message, response)
    this.responseBody = body
    this.response = response
    this.errorCode = errorCode
    this.statusCode = statusCode
  }
 
  static unknown(response: Response) {
    return new RequestError('Unknown error', undefined, response.status, response.statusText, response)
  }
 
  static fromPlainError(body: ErrorPlainResponse, response: Response) {
    return new RequestError(body.error, body, response.status, response.statusText, response)
  }
 
  static fromErrorResponse(body: ErrorResponse, response: Response) {
    return new RequestError(body.error.message, body, response.status, body.error.code, response)
  }
}
 
/**
 * Error that indicate that the request was throttled.
 * */
export class TooManyRequestsError extends RequestError<429, ErrorResponse> {
  /**
   * Number of seconds to wait before retrying the request.
   * @remarks
   * The value is parsed from the `Retry-After` header of the response.
   */
  readonly retryAfter: number = 0
 
  constructor(body: ErrorResponse, response: Response) {
    super(body.error.message, body, 429, body.error.code, response)
    this.retryAfter = getRetryAfter(response)
  }
 
  static fromPlain(error: ErrorPlainResponse, response: Response) {
    return new TooManyRequestsError(
      {
        error: {
          message: error.error,
          code: 'TooManyRequests',
        },
      },
      response
    )
  }
}