axios-get-json-response
A simple utility for checking status codes and parsing JSON data from Axios responses. While Axios can do this by itself, it doesn't document any distinguishable error types, and so when an error occurs you can never know what went wrong.
This library fixes that, by giving you two distinct error types. Hopefully this functionality eventually makes it into Axios itself.
Both error types correctly inherit from Error, and therefore a) have stacktraces, and b) can be used with instanceof
as well as things based on it, like Bluebird's filtered .catch
.
Examples
An existent and valid URL:
"use strict"; const axios = ;const Promise = ;const getJson = ; Promise;
Using axios.create
to set the custom configuration as a default, and showing the result for an existent URL that is not valid JSON:
"use strict"; const axios = ;const Promise = ;const getJson = ; let manualAxios = axios; Promise;
The result for a non-existent URL:
"use strict"; const axios = ;const Promise = ;const getJson = ; let manualAxios = axios; Promise;
API
getJson.axiosConfiguration
Some preset configuration options, that disable response code checking and body parsing in Axios. Needed for this library to work. These options are fed directly into Axios; see the example.
getJson.parse(response, [options])
Validates the status code and parses the response body. Returns the parsed JSON if successful, or throws either a BadStatusCode
or ParsingFailed
error depending on what went wrong (see below).
- response: The Axios response object to handle.
- options: Optional.
- validateStatus: Optional. A custom status code validation function, like in Axios. Defaults to the same as in Axios (all 2XX are considered valid). Expected to return
true
for a valid/expected status code, andfalse
for an unexpected one.
- validateStatus: Optional. A custom status code validation function, like in Axios. Defaults to the same as in Axios (all 2XX are considered valid). Expected to return
getJson.BadStatusCode
An error type that signifies that an unexpected status code was received.
Extra properties on this error object:
- statusCode: The received status code.
getJson.ParsingFailed
An error type that signifies that the response body could not be parsed as JSON.
Changelog
1.0.1 (August 30, 2019)
- Removed erroneous
console.log
.
1.0.0 (August 30, 2019)
Initial release.