All files / src/errors handleErrorResponse.ts

100% Statements 13/13
100% Branches 15/15
100% Functions 3/3
100% Lines 13/13

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  8x     25x                       9x     8x 25x 16x 3x     13x     9x 7x 2x     5x     2x    
import { ErrorPlainResponse, ErrorResponse } from '../types'
import { RequestError, TooManyRequestsError } from './apiErrors'
 
function isErrorResponse(value: unknown): value is ErrorResponse {
  return Boolean(
    value &&
      typeof value === 'object' &&
      'error' in value &&
      typeof value.error === 'object' &&
      value.error &&
      'code' in value.error &&
      'message' in value.error
  )
}
 
function isPlainErrorResponse(value: unknown): value is ErrorPlainResponse {
  return Boolean(value && typeof value === 'object' && 'error' in value && typeof value.error === 'string')
}
 
export function handleErrorResponse(json: any, response: Response): never {
  if (isErrorResponse(json)) {
    if (response.status === 429) {
      throw new TooManyRequestsError(json, response)
    }
 
    throw RequestError.fromErrorResponse(json, response)
  }
 
  if (isPlainErrorResponse(json)) {
    if (response.status === 429) {
      throw TooManyRequestsError.fromPlain(json, response)
    }
 
    throw RequestError.fromPlainError(json, response)
  }
 
  throw RequestError.unknown(response)
}