Skip to content

Error Handling

Every function namespace in Ox exports an accompanying error type (ErrorType) and parser (parseError) that you can use to strongly type your catch statements, or inject into a custom type-safe error handling library (e.g. neverthrow, Effect, etc.).

Usage with Vanilla TypeScript

Unfortunately, TypeScript doesn't have an abstraction for typed exceptions, so the most pragmatic & vanilla approach would be to explicitly cast error types in the catch statement with the function's .ErrorType property.

import { AbiParameters, Errors, Hex } from 'ox'
 
try {
  AbiParameters.encode(
    AbiParameters.from('address'), 
    ['0xc961145a54c96e3ae9baa048c4f4d6b04c13916b']
  )
} catch (err) {
  const error = err as AbiParameters.encode.ErrorType
  error.
name: "Error" | "AbiParameters.LengthMismatchError" | "Hex.IntegerOutOfRangeError" | "Hex.SizeExceedsPaddingSizeError" | "AbiParameters.InvalidArrayError" | "AbiParameters.ArrayLengthMismatchError" | "Address.InvalidAddressError" | "Hex.SizeOverflowError" | "Hex.SliceOffsetOutOfBoundsError" | "AbiParameters.InvalidTypeError"
name
if (error.name === 'Address.InvalidAddressError') error.cause.
name: "Address.InvalidInputError" | "Address.InvalidChecksumError"
name
}

Usage with neverthrow

You can utilize Ox's .ErrorType property into custom type-safe error handling libraries like neverthrow.

import { AbiParameters } from 'ox'
import { fromThrowable } from 'neverthrow';
 
const encode = fromThrowable(
  AbiParameters.encode,
  e => e as AbiParameters.encode.ErrorType
)
 
const result = encode(AbiParameters.from('bytes'), ['0xdeadbeef'])
 
if (result.isErr())
	result.error.
name: "Error" | "AbiParameters.LengthMismatchError" | "Hex.IntegerOutOfRangeError" | "Hex.SizeExceedsPaddingSizeError" | "AbiParameters.InvalidArrayError" | "AbiParameters.ArrayLengthMismatchError" | "Address.InvalidAddressError" | "Hex.SizeOverflowError" | "Hex.SliceOffsetOutOfBoundsError" | "AbiParameters.InvalidTypeError"
name