retry based on response content #776
-
|
Hello, I would like to know the best way to retry a request based on the content of the response. I saw that the Example: {
"error": {
"code":"A_RETRIABLE_ERROR_CODE",
"message":"This error can be retried"
}
}Thanks! |
Beta Was this translation helpful? Give feedback.
Answered by
sindresorhus
Oct 23, 2025
Replies: 2 comments 4 replies
-
|
You should be able to read import ky, {HTTPError} from 'ky';
const json = await ky('https://example.com', {
retry: {
limit: 3,
shouldRetry: ({error, retryCount}) => {
// Retry on specific business logic errors from API
if (error instanceof HTTPError) {
const status = error.response.status;
// Retry on 429 (rate limit) but only for first 2 attempts
if (status === 429 && retryCount <= 2) {
return true;
}
// Don't retry on 4xx errors except rate limits
if (status >= 400 && status < 500) {
return false;
}
}
// Use default retry logic for other errors
return undefined;
}
}
}).json(); |
Beta Was this translation helpful? Give feedback.
1 reply
-
|
You can throw from import ky from 'ky';
const api = ky.extend({
retry: {
limit: 3,
},
hooks: {
afterResponse: [
async (_request, _options, response) => {
if (response.status === 200) {
const data = await response.clone().json();
if (data.error?.code === 'A_RETRIABLE_ERROR_CODE') {
return ky.retry();
}
}
}
]
}
}); |
Beta Was this translation helpful? Give feedback.
3 replies
Answer selected by
sindresorhus
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can throw from
afterResponseand useky.retry()to catch it: