-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror-handling-retry.ts
More file actions
129 lines (114 loc) · 2.8 KB
/
error-handling-retry.ts
File metadata and controls
129 lines (114 loc) · 2.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/**
* Advanced Example: Error Handling with Retry Logic
*
* This example demonstrates how to implement robust error handling
* with exponential backoff retry logic for API calls.
*/
import { Api, Payment } from '@volverjs/satispay-node-sdk'
// Configure API
Api.setEnv('production')
Api.setKeyId('your-key-id')
Api.setPrivateKey('your-private-key')
/**
* Retry configuration
*/
interface RetryConfig {
maxRetries: number
initialDelay: number
maxDelay: number
backoffMultiplier: number
}
const defaultRetryConfig: RetryConfig = {
maxRetries: 3,
initialDelay: 1000, // 1 second
maxDelay: 10000, // 10 seconds
backoffMultiplier: 2,
}
/**
* Sleep helper
*/
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms))
}
/**
* Retry wrapper with exponential backoff
*/
async function retryWithBackoff<T>(
fn: () => Promise<T>,
config: RetryConfig = defaultRetryConfig
): Promise<T> {
let lastError: Error | undefined
let delay = config.initialDelay
for (let attempt = 0; attempt <= config.maxRetries; attempt++) {
try {
return await fn()
} catch (error) {
lastError = error as Error
// Don't retry on client errors (4xx)
if (error instanceof Error && error.message.includes('400')) {
throw error
}
if (attempt < config.maxRetries) {
console.log(
`Attempt ${attempt + 1} failed: ${lastError.message}. Retrying in ${delay}ms...`
)
await sleep(delay)
delay = Math.min(delay * config.backoffMultiplier, config.maxDelay)
}
}
}
throw new Error(
`Max retries (${config.maxRetries}) exceeded. Last error: ${lastError?.message}`
)
}
/**
* Create payment with retry logic
*/
async function createPaymentWithRetry(
amount: number,
description: string
): Promise<any> {
return retryWithBackoff(async () => {
return await Payment.create({
flow: 'MATCH_CODE',
amount_unit: amount,
currency: 'EUR',
external_code: `ORDER-${Date.now()}`,
metadata: {
description,
timestamp: new Date().toISOString(),
},
})
})
}
/**
* Get payment with retry logic
*/
async function getPaymentWithRetry(paymentId: string): Promise<any> {
return retryWithBackoff(async () => {
return await Payment.get(paymentId)
})
}
/**
* Example usage
*/
async function main() {
try {
// Create payment with automatic retries
console.log('Creating payment with retry logic...')
const payment = await createPaymentWithRetry(
1000, // 10.00 EUR
'Test payment with retry logic'
)
console.log('Payment created:', payment)
// Get payment with automatic retries
console.log('\nGetting payment with retry logic...')
const fetchedPayment = await getPaymentWithRetry(payment.id)
console.log('Payment retrieved:', fetchedPayment)
} catch (error) {
console.error('Error:', error)
process.exit(1)
}
}
// Run example
main()