@@ -51,6 +51,26 @@ function formatErrorMessage(err: unknown): string {
5151 return String ( err ) ;
5252}
5353
54+ function readTelegramErrorCode ( err : unknown ) : number | undefined {
55+ if ( err && typeof err === "object" && "error_code" in err ) {
56+ const code = ( err as { error_code : unknown } ) . error_code ;
57+ if ( typeof code === "number" ) {
58+ return code ;
59+ }
60+ }
61+ return undefined ;
62+ }
63+
64+ function postPollError ( err : unknown ) : void {
65+ const errorCode = readTelegramErrorCode ( err ) ;
66+ post ( {
67+ type : "poll-error" ,
68+ message : formatErrorMessage ( err ) ,
69+ ...( errorCode === undefined ? { } : { errorCode } ) ,
70+ finishedAt : Date . now ( ) ,
71+ } ) ;
72+ }
73+
5474function resolveBackoff ( attempt : number ) : number {
5575 return Math . min ( retryMaxMs , retryInitialMs * 2 ** Math . max ( 0 , attempt - 1 ) ) ;
5676}
@@ -122,15 +142,21 @@ async function fetchJson(params: {
122142 } ) ;
123143 const json = ( await response . json ( ) ) as {
124144 ok ?: unknown ;
145+ error_code ?: unknown ;
125146 result ?: unknown ;
126147 description ?: unknown ;
127148 } ;
128149 if ( ! response . ok || json . ok !== true ) {
129- throw new Error (
150+ const message =
130151 typeof json . description === "string"
131152 ? json . description
132- : `Telegram getUpdates failed with HTTP ${ response . status } ` ,
133- ) ;
153+ : `Telegram getUpdates failed with HTTP ${ response . status } ` ;
154+ // Preserve the Bot API error_code across the worker boundary so the
155+ // parent session can distinguish getUpdates conflicts (409) from fatal
156+ // errors (401) without parsing description strings.
157+ throw typeof json . error_code === "number"
158+ ? Object . assign ( new Error ( message ) , { error_code : json . error_code } )
159+ : new Error ( message ) ;
134160 }
135161 return json . result ;
136162 } finally {
@@ -195,11 +221,7 @@ async function main(): Promise<void> {
195221 break ;
196222 }
197223 failures += 1 ;
198- post ( {
199- type : "poll-error" ,
200- message : formatErrorMessage ( err ) ,
201- finishedAt : Date . now ( ) ,
202- } ) ;
224+ postPollError ( err ) ;
203225 if ( ! isRecoverableTelegramNetworkError ( err , { context : "polling" } ) ) {
204226 throw err ;
205227 }
@@ -216,7 +238,7 @@ main()
216238 parentPort ?. close ( ) ;
217239 } )
218240 . catch ( ( err : unknown ) => {
219- post ( { type : "poll-error" , message : formatErrorMessage ( err ) , finishedAt : Date . now ( ) } ) ;
241+ postPollError ( err ) ;
220242 parentPort ?. close ( ) ;
221243 process . exitCode = stopped ? 0 : 1 ;
222244 } ) ;
0 commit comments