Request Retry
.retry(retryTimes[, retryDelay[, retryOn]])
| Parameter | Default | Description |
|---|---|---|
| retryTimes | 0 | Maximum number of retries |
| retryDelay | 0 | Interval between retries (in milliseconds) |
| retryOn | (attempt, error) => !!error | Whether to continue with the next retry |
Example
import { request } from 'keq'
import { throwException, RequestException } from 'keq-exception'
await request
.get('/cat')
.retry(2, 1000, (attempt, err, context) => {
// error is a fetch() exception, retry is recommended. Example: browser suddenly loses network.
if (err) return true
if (context.response) {
if (context.response.status >= 400 && context.response.status < 500) {
// 400 is usually a business-defined error, no need to retry
return false
} else if (context.response.status >= 500) {
// 500 is usually a server-side system exception, needs retry
return true
}
}
})With keq-exception, you can more elegantly integrate error handling and retry strategy code:
import { request } from 'keq'
import { throwException, RequestException } from 'keq-exception'
request
.use(throwException(async (context) => {
if (context.response) {
if (context.response.status >= 400 && context.response.status < 500) {
throw new RequestException(context.response.status, context.response.statusText, false)
} else if (context.response.status >= 500) {
throw new RequestException(context.response.status, context.response.statusText)
}
}
}))
try {
await request
.get('/cat')
.retry(2, 1000)
} catch (err) {
// When both retries fail or retry is terminated, RequestException will be caught
console.log(err instanceof RequestException)
}