refactor: implement error handling and retry logic in state loop for improved resilience

This commit is contained in:
MayaTheShy
2026-02-20 03:54:07 -05:00
parent 2686ca4697
commit 7385c258d5

View File

@@ -290,6 +290,8 @@ export class Turtle extends EventEmitter {
*/
async _runStateLoop() {
const state = this._state;
let consecutiveErrors = 0;
const MAX_CONSECUTIVE_ERRORS = 5;
try {
const generator = state.act();
@@ -299,9 +301,23 @@ export class Turtle extends EventEmitter {
if (this._state !== state) {
return; // State changed, stop this generator
}
// Reset error counter on successful iteration
consecutiveErrors = 0;
}
} 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);
this.setState('idle');
}