brainy/src/transaction/errors.ts

102 lines
2.6 KiB
TypeScript
Raw Normal View History

/**
* Transaction System Errors
*
* Provides detailed error information for transaction failures.
*/
/**
* Base class for all transaction errors
*/
export class TransactionError extends Error {
constructor(
message: string,
public readonly context?: Record<string, any>
) {
super(message)
this.name = 'TransactionError'
Error.captureStackTrace(this, this.constructor)
}
}
/**
* Error during transaction execution
*/
export class TransactionExecutionError extends TransactionError {
constructor(
message: string,
public readonly operationIndex: number,
public readonly operationName: string | undefined,
public override readonly cause: Error
) {
super(message, {
operationIndex,
operationName,
cause: cause.message
})
this.name = 'TransactionExecutionError'
}
}
/**
* Error during transaction rollback
*/
export class TransactionRollbackError extends TransactionError {
constructor(
message: string,
public readonly originalError: Error,
public readonly rollbackErrors: Error[]
) {
super(message, {
originalError: originalError.message,
rollbackErrorCount: rollbackErrors.length,
rollbackErrors: rollbackErrors.map(e => e.message)
})
this.name = 'TransactionRollbackError'
}
}
/**
* Error for invalid transaction state
*/
export class InvalidTransactionStateError extends TransactionError {
constructor(
currentState: string,
attemptedAction: string
) {
super(
`Cannot ${attemptedAction}: transaction is in state '${currentState}'`,
{ currentState, attemptedAction }
)
this.name = 'InvalidTransactionStateError'
}
}
/**
* Error for transaction timeout
*/
export class TransactionTimeoutError extends TransactionError {
constructor(
timeoutMs: number,
operationIndex: number,
telemetry?: {
elapsedMs?: number
totalOperations?: number
operationName?: string
}
) {
const progress =
telemetry?.totalOperations !== undefined
? `${operationIndex}/${telemetry.totalOperations}`
: String(operationIndex)
const name = telemetry?.operationName ? ` ('${telemetry.operationName}')` : ''
const elapsed =
telemetry?.elapsedMs !== undefined ? `${telemetry.elapsedMs}ms elapsed, ` : ''
super(
`Transaction timed out at operation ${progress}${name}${elapsed}budget ${timeoutMs}ms. ` +
`The batch rolled back atomically; retry with a higher timeoutMs or a smaller batch.`,
{ timeoutMs, operationIndex, ...telemetry }
)
this.name = 'TransactionTimeoutError'
}
}