Skip to content

Commit

Permalink
feat: log additionally axios error (#6)
Browse files Browse the repository at this point in the history
* feat: log additionally axios error
  • Loading branch information
vyancharuk authored Jan 14, 2021
1 parent e326ce0 commit 8249571
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions lib/responseBuilder.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,43 @@ module.exports = function ResponseBuilder() {
return response;
};

/**
* Return error object with only necessary props according to axios docs https://github.com/axios/axios#handling-errors
* @param {Error} axiosError axios error object
* @return {number} http code
* @private
*/
self._getAxiosError = (axiosError) => {
const errorInfo = {
config: axiosError.config,
};

if (axiosError.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
return {
...errorInfo,
data: axiosError.response.data,
status: axiosError.response.status,
headers: axiosError.response.headers,
};
}
if (axiosError.request) {
// The request was made but no response was received
// `error.request` is an instance of http.ClientRequest in node.js
return {
...errorInfo,
request: axiosError.request,
};
}

// Something happened in setting up the request that triggered an Error
return {
...errorInfo,
message: axiosError.message,
};
};

/**
* Handle error response
* @param {Error} error error object or something and inheirits from it
Expand All @@ -60,6 +97,10 @@ module.exports = function ResponseBuilder() {
* @private
*/
self._errorResponse = (error, codeOverride, req) => {
if (error && error.isAxiosError) {
log.error(`@backend-utils:errorResponse - error:axios:${JSON.stringify(self._getAxiosError(error))}`);
}

if (!(error instanceof Error)) {
if (error instanceof String) {
return self._errorResponse(new VError(error), codeOverride);
Expand Down

0 comments on commit 8249571

Please sign in to comment.