Skip to content

Commit

Permalink
fix: improve request errors
Browse files Browse the repository at this point in the history
Signed-off-by: getlarge <ed@getlarge.eu>
  • Loading branch information
getlarge committed Mar 10, 2021
1 parent 597ac56 commit 656de69
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 33 deletions.
24 changes: 12 additions & 12 deletions src/baseRequest.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,24 @@
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0

import {
Promise
} from 'es6-promise'
import { Promise } from 'es6-promise'
import fetchPonyfill from 'fetch-ponyfill'
import {
vsprintf
} from 'sprintf-js'
import { vsprintf } from 'sprintf-js'

import formatText from './format_text'
import stringifyAsQueryParam from './stringify_as_query_param'

const fetch = fetchPonyfill(Promise)

export function ResponseError(message, status, requestURI) {
this.name = 'ResponseError'
this.message = message
this.status = status
this.requestURI = requestURI
this.stack = (new Error()).stack
}

ResponseError.prototype = new Error;

/**
* @private
Expand Down Expand Up @@ -45,12 +50,7 @@ function handleResponse(res) {
// If status is not a 2xx (based on Response.ok), assume it's an error
// See https://developer.mozilla.org/en-US/docs/Web/API/GlobalFetch/fetch
if (!(res && res.ok)) {
const errorObject = {
message: 'HTTP Error: Requested page not reachable',
status: `${res.status} ${res.statusText}`,
requestURI: res.url
}
throw errorObject
throw new ResponseError('HTTP Error: Requested page not reachable', `${res.status} ${res.statusText}`, res.url)
}
return res
}
Expand Down
35 changes: 14 additions & 21 deletions src/transport.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,28 +46,21 @@ export default class Transport {
connection = this.pickConnection()
// Date in milliseconds
const startTime = Date.now()
try {
// eslint-disable-next-line no-await-in-loop
response = await connection.request(
path,
headers,
this.timeout,
this.maxBackoffTime
)
const elapsed = Date.now() - startTime
if (connection.backoffTime > 0 && this.timeout > 0) {
this.timeout -= elapsed
} else {
// No connection error, the response is valid
return response
}
} catch (err) {
throw err
// eslint-disable-next-line no-await-in-loop
response = await connection.request(
path,
headers,
this.timeout,
this.maxBackoffTime
)
const elapsed = Date.now() - startTime
if (connection.backoffTime > 0 && this.timeout > 0) {
this.timeout -= elapsed
} else {
// No connection error, the response is valid
return response
}
}
const errorObject = {
message: 'TimeoutError',
}
throw errorObject
throw new Error('TimeoutError')
}
}

0 comments on commit 656de69

Please sign in to comment.