feat(errors): timeout error and set prototype

This commit is contained in:
enes 2025-01-09 17:20:59 +01:00
parent df27451c46
commit dddabbc1d1
2 changed files with 17 additions and 3 deletions

View File

@ -42,8 +42,8 @@ export class BaseError extends Error {
super(message, { cause: cause })
this.name = this.constructor.name
this.context = context
Object.setPrototypeOf(this, BaseError.prototype)
}
}
@ -56,3 +56,15 @@ export function errorFeedback(error: unknown) {
log(true, LogType.Error, error)
}
}
export class TimeoutError extends Error {
constructor(timeoutMs?: number) {
let message = 'Time elapsed.'
if (timeoutMs) {
message += `\n* ${timeoutMs}ms`
}
super(message)
this.name = this.constructor.name
Object.setPrototypeOf(this, TimeoutError.prototype)
}
}

View File

@ -1,3 +1,5 @@
import { TimeoutError } from 'types'
export enum LogType {
Info = 'info',
Error = 'error',
@ -23,14 +25,14 @@ export const log = (
/**
* Creates a promise that rejects with a timeout error after a specified duration.
* @param ms The duration in milliseconds after which the promise should reject. Defaults to 60000 milliseconds (1 minute).
* @returns A promise that rejects with an Error('Timeout') after the specified duration.
* @returns A promise that rejects with an TimeoutError after the specified duration.
*/
export const timeout = (ms: number = 60000) => {
return new Promise<never>((_, reject) => {
// Set a timeout using setTimeout
setTimeout(() => {
// Reject the promise with an Error indicating a timeout
reject(new Error('Timeout'))
reject(new TimeoutError(ms))
}, ms) // Timeout duration in milliseconds
})
}