Function throwOnUnexpectedApiResponse

  • Throws an exception on an unexpected API response.

    Parameters

    • response: AxiosResponse

      The response context.

    • expectedStatusCodes: number[]

      One or more expected HTTP status codes.

    • Optional errorMessages: Nilable<ApiResponseErrorMessages>

      An optional repository of error messages by status code.

    Returns Promise<void>

    Example

    import axios from "axios"
    import { throwOnUnexpectedApiResponse } from "@egomobile/api-utils"

    const response = await axios.get("https://api.example.com")

    // we expect `200` as response
    await throwOnUnexpectedApiResponse(response, 200)

    // same as an array, which makes it possible to expect more than
    // one possible status code
    await throwOnUnexpectedApiResponse(response, [200])

    // as validator function
    await throwOnUnexpectedApiResponse(response, (context) => context.response.status === 200)

    // this will throw special errors messages, for status codes beginning with 4 or 5
    //
    // the first match always "wins"
    //
    // following template placeholders are supported:
    // - {{body}} => response body as text with a maximum length of 131072 chars
    // - {{headers}} => list of HTTP response headers as one single text
    // - {{messages}} => list of extracted API messages items as one single text
    // - {{statusCode}} => HTTP status code, like 200, 404, 500 etc.
    // - {{statusText}} => text representation of HTTP status code, like `OK`, `Not Found`, `Internal Server Error` etc.
    //
    await throwOnUnexpectedApiResponse(response, 200, {
    "^4": "Unexpected client error: {{statusCode}} {{statusText}}\n\n{{body}}",
    "^5": "Unexpected server error: {{statusCode}} {{statusText}}\n\n{{body}}"
    })
  • Parameters

    • response: AxiosResponse
    • expectedStatusCode: number
    • Optional errorMessages: Nilable<ApiResponseErrorMessages>

    Returns Promise<void>

  • Parameters

    • response: AxiosResponse
    • validator: ApiResponseValidator
    • Optional errorMessages: Nilable<ApiResponseErrorMessages>

    Returns Promise<void>

Generated using TypeDoc