refactor: implement error handling and retry logic in state loop for improved resilience
This commit is contained in:
@@ -290,6 +290,8 @@ export class Turtle extends EventEmitter {
|
|||||||
*/
|
*/
|
||||||
async _runStateLoop() {
|
async _runStateLoop() {
|
||||||
const state = this._state;
|
const state = this._state;
|
||||||
|
let consecutiveErrors = 0;
|
||||||
|
const MAX_CONSECUTIVE_ERRORS = 5;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const generator = state.act();
|
const generator = state.act();
|
||||||
@@ -299,9 +301,23 @@ export class Turtle extends EventEmitter {
|
|||||||
if (this._state !== state) {
|
if (this._state !== state) {
|
||||||
return; // State changed, stop this generator
|
return; // State changed, stop this generator
|
||||||
}
|
}
|
||||||
|
// Reset error counter on successful iteration
|
||||||
|
consecutiveErrors = 0;
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (this._state === state) {
|
if (this._state !== state) return;
|
||||||
|
|
||||||
|
consecutiveErrors++;
|
||||||
|
const isTimeout = error.message?.includes('timed out');
|
||||||
|
|
||||||
|
if (isTimeout && consecutiveErrors < MAX_CONSECUTIVE_ERRORS) {
|
||||||
|
console.warn(`[Turtle ${this.id}] Timeout in ${state.name} (${consecutiveErrors}/${MAX_CONSECUTIVE_ERRORS}), retrying...`);
|
||||||
|
// Wait a bit then restart the state loop
|
||||||
|
await new Promise(r => setTimeout(r, 2000));
|
||||||
|
if (this._state === state) {
|
||||||
|
this._runStateLoop(); // Restart the loop with the same state
|
||||||
|
}
|
||||||
|
} else {
|
||||||
console.error(`[Turtle ${this.id}] State error in ${state.name}:`, error.message);
|
console.error(`[Turtle ${this.id}] State error in ${state.name}:`, error.message);
|
||||||
this.setState('idle');
|
this.setState('idle');
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user