Add stack traces to promiseTimeout & delay

This commit is contained in:
Adhiraj Singh
2021-01-05 17:42:05 +05:30
parent 96a6dc7e6d
commit 0565444999
2 changed files with 10 additions and 6 deletions

View File

@@ -45,15 +45,18 @@ export class BaileysError extends Error {
status?: number
context: any
constructor (message: string, context: any) {
constructor (message: string, context: any, stack?: string) {
super (message)
this.name = 'BaileysError'
this.status = context.status
this.context = context
if(stack) {
this.stack = stack
}
}
}
export const TimedOutError = () => new BaileysError ('timed out', { status: 408 })
export const CancelledError = () => new BaileysError ('cancelled', { status: 500 })
export const TimedOutError = (stack?: string) => new BaileysError ('timed out', { status: 408 })
export const CancelledError = (stack?: string) => new BaileysError ('cancelled', { status: 500 })
export interface WAQuery {
json: any[] | WANode

View File

@@ -103,6 +103,7 @@ export const unixTimestampSeconds = (date: Date = new Date()) => Math.floor(date
export const delay = (ms: number) => delayCancellable (ms).delay
export const delayCancellable = (ms: number) => {
const stack = new Error().stack
let timeout: NodeJS.Timeout
let reject: (error) => void
const delay: Promise<void> = new Promise((resolve, _reject) => {
@@ -111,18 +112,18 @@ export const delayCancellable = (ms: number) => {
})
const cancel = () => {
clearTimeout (timeout)
reject (CancelledError())
reject (CancelledError(stack))
}
return { delay, cancel }
}
export async function promiseTimeout<T>(ms: number, promise: (resolve: (v?: T)=>void, reject: (error) => void) => void) {
if (!ms) return new Promise (promise)
const stack = new Error().stack
// Create a promise that rejects in <ms> milliseconds
let {delay, cancel} = delayCancellable (ms)
const p = new Promise ((resolve, reject) => {
delay
.then(() => reject(TimedOutError()))
.then(() => reject(TimedOutError(stack)))
.catch (err => reject(err))
promise (resolve, reject)