Skip to content

Class: Err<T, E>

Defined in: core/err.ts:26

Internal

Represents an error Result containing a failure.

Err is a Result variant that encapsulates failed operations. Provides methods for recovery, error transformation, and conversion to other representations, maintaining type-safety.

Remarks

You normally don't instantiate Err directly. Use Result.err(error).

Example

ts
const result = Result.err(new Error('failed'))
console.log(result.unwrapErr()) // Error: failed
console.log(result.isErr()) // true

Type Parameters

T

T = never

Success value type (for compatibility)

E

E = Error

Error type

Implements

  • ResultMethods<T, E>

Constructors

Constructor

new Err<T, E>(error): Err<T, E>

Defined in: core/err.ts:29

Parameters

error

E

Returns

Err<T, E>

Accessing

err

Get Signature

get err(): E

Defined in: core/err.ts:142

Gets the error or null.

Read-only property for safe error access.

Examples
ts
const result = Result.err('fail')
console.log(result.err) // "fail"
ts
const ok = Result.ok(42)
console.log(ok.err) // null
Returns

E

The encapsulated error

Implementation of

ResultMethods.err


ok

Get Signature

get ok(): null

Defined in: core/err.ts:122

Gets the success value or null.

Example
ts
Result.err('fail').ok // null
Returns

null

Always null for Err

Implementation of

ResultMethods.ok


expect()

expect(message): never

Defined in: core/err.ts:254

Attempts to extract value with custom message (always fails for Err).

Parameters

message

string

Error message

Returns

never

Never returns

Throws

Throws with custom message and original error as cause

Example

ts
Result.err(new Error('fail')).expect('should exist')
// throws Error("should exist", {
//   cause: Error("fail")
// })

Implementation of

ResultMethods.expect


expectErr()

expectErr(_message): E

Defined in: core/err.ts:271

Extracts error with custom message.

For Err, ignores the message and returns the error.

Parameters

_message

string

Error message (ignored for Err)

Returns

E

The encapsulated error

Example

ts
Result.err('fail').expectErr('should be error')
// "fail"

Implementation of

ResultMethods.expectErr


unwrap()

unwrap(): never

Defined in: core/err.ts:159

Attempts to extract the success value (always fails for Err).

Returns

never

Never returns

Throws

Always throws error with original cause

Example

ts
Result.err(new Error('fail')).unwrap()
// throws Error("Called unwrap on an Err value", {
//   cause: Error("fail")
// })

Implementation of

ResultMethods.unwrap


unwrapErr()

unwrapErr(): E

Defined in: core/err.ts:183

Extracts the error.

For Err, returns the encapsulated error. Use when you're sure the Result is Err.

Returns

E

The encapsulated error

Examples

ts
const err = Result.err('failed').unwrapErr()
console.log(err) // "failed"
ts
// Usage after checking
if (result.isErr()) {
  const error = result.unwrapErr() // safe
  console.error('Operation failed:', error)
}

Implementation of

ResultMethods.unwrapErr


unwrapOr()

unwrapOr(defaultValue): T

Defined in: core/err.ts:206

Extracts value or returns default.

For Err, returns the provided default value. For Ok, would return the encapsulated value.

Parameters

defaultValue

T

Default value to return

Returns

T

The default value

See

unwrapOrElse for computed default

Examples

ts
Result.err('fail').unwrapOr(42) // 42
Result.ok(99).unwrapOr(42) // 99
ts
// Providing default value in operation
const age = getAge().unwrapOr(18)

Implementation of

ResultMethods.unwrapOr


unwrapOrElse()

unwrapOrElse(onError): T

Defined in: core/err.ts:236

Extracts value or computes default from error.

Allows generating fallback value based on specific error.

Parameters

onError

(error) => T

Default value generator

Returns

T

Value computed from error

See

unwrapOr for static default

Examples

ts
Result.err('not found').unwrapOrElse((error) => {
  console.log('Error:', error)
  return 0
})
// logs "Error: not found", returns 0
ts
// Recovery based on error type
result.unwrapOrElse((error) => {
  if (error.code === 404) return []
  if (error.code === 500) throw error

  return defaultValue
})

Implementation of

ResultMethods.unwrapOrElse

Async

andAsync()

andAsync<U>(_result): AsyncResult<U, E>

Defined in: core/err.ts:883

Returns async Result if this is Ok (not applicable for Err).

Type Parameters

U

U

Second Result success type

Parameters

_result

AsyncResult<U, E>

Async Result (ignored)

Returns

AsyncResult<U, E>

Promise of Err with same error

Example

ts
await Result.err('fail').andAsync(
  Promise.resolve(Result.ok(42))
)
// Err("fail")

Implementation of

ResultMethods.andAsync


andThenAsync()

andThenAsync<U>(_mapAsync): AsyncResult<U, E>

Defined in: core/err.ts:865

Chains async operation that returns Result (not applicable for Err).

Type Parameters

U

U

New success type

Parameters

_mapAsync

(value) => AsyncResult<U, E>

Chaining (ignored)

Returns

AsyncResult<U, E>

Promise of Err with same error

Example

ts
await Result.err('fail').andThenAsync(
  async (x) => Result.ok(x * 2)
)
// Err("fail")

Implementation of

ResultMethods.andThenAsync


mapAsync()

mapAsync<U>(_mapperAsync): AsyncResult<U, E>

Defined in: core/err.ts:779

Transforms value asynchronously (not applicable for Err).

For Err, keeps the error unchanged and only adjusts value type.

Type Parameters

U

U

Transformed value type

Parameters

_mapperAsync

(value) => Promise<U>

Async Transformation (ignored)

Returns

AsyncResult<U, E>

Promise of Err with same error

Example

ts
await Result.err('fail').mapAsync(async (x) => x * 2)
// Err("fail")

Implementation of

ResultMethods.mapAsync


mapErrAsync()

mapErrAsync<E2>(mapperAsync): AsyncResult<T, E2>

Defined in: core/err.ts:807

Transforms error asynchronously.

Async version of mapErr().

Type Parameters

E2

E2

New error type

Parameters

mapperAsync

(error) => Promise<E2>

Async transformation

Returns

AsyncResult<T, E2>

Promise of Err with transformed error

Examples

ts
await Result.err('fail').mapErrAsync(
  async (e) => new Error(e)
)
// Err(Error: fail)
ts
// Enriching error with async data
await result.mapErrAsync(async (error) => ({
  ...error,
  context: await fetchContext(),
  timestamp: Date.now()
}))

Implementation of

ResultMethods.mapErrAsync


mapOrAsync()

mapOrAsync<U>(_mapperAsync, defaultValue): Promise<U>

Defined in: core/err.ts:824

Transforms value asynchronously or returns default.

Type Parameters

U

U

Transformed value type

Parameters

_mapperAsync

(value) => Promise<U>

Transformation (ignored)

defaultValue

U

Default value

Returns

Promise<U>

Promise of default value

Example

ts
await Result.err('fail').mapOrAsync(async (x) => x * 2, 0)
// 0

Implementation of

ResultMethods.mapOrAsync


mapOrElseAsync()

mapOrElseAsync<U>(_okAsync, errAsync): Promise<U>

Defined in: core/err.ts:844

Transforms using appropriate async mapper.

Type Parameters

U

U

Result type

Parameters

_okAsync

(value) => Promise<U>

Success mapper (ignored)

errAsync

(error) => Promise<U>

Async error mapper

Returns

Promise<U>

Promise of result from error mapper

Example

ts
await Result.err('fail').mapOrElseAsync(
  async (x) => x * 2,
  async (e) => -1
)
// -1

Implementation of

ResultMethods.mapOrElseAsync


orAsync()

orAsync(result): AsyncResult<T, E>

Defined in: core/err.ts:902

Returns this Result or async alternative.

For Err, returns the alternative Promise.

Parameters

result

AsyncResult<T, E>

Async alternative Result

Returns

AsyncResult<T, E>

The provided Promise

Example

ts
await Result.err('fail').orAsync(
  Promise.resolve(Result.ok(42))
)
// Ok(42)

Implementation of

ResultMethods.orAsync


orElseAsync()

orElseAsync(onErrorAsync): AsyncResult<T, E>

Defined in: core/err.ts:926

Returns this Result or executes async recovery.

For Err, executes async recovery function.

Parameters

onErrorAsync

(error) => AsyncResult<T, E>

Async recovery

Returns

AsyncResult<T, E>

Promise of recovered Result

Examples

ts
await Result.err('not found').orElseAsync(
  async (e) => Result.ok(await fetchDefault())
)
ts
// Async fallback chain
await result
  .orElseAsync(async () => fetchFromCache())
  .then(r => r.orElseAsync(async () => fetchFromAPI()))

Implementation of

ResultMethods.orElseAsync

Chaining

and()

and<U>(result): Result<U, E>

Defined in: core/err.ts:462

Returns second Result if this is Ok (not applicable for Err).

Type Parameters

U

U

Second Result success type

Parameters

result

Result<U, E>

Result (ignored)

Returns

Result<U, E>

Err with same error

See

Example

ts
Result.err('fail').and(Result.ok(42))
// Err("fail")

Implementation of

ResultMethods.and


andThen()

andThen<U>(_flatMapper): Result<U, E>

Defined in: core/err.ts:486

Chains operation that returns Result (not applicable for Err).

For Err, keeps the error ignoring the function.

Type Parameters

U

U

New success type

Parameters

_flatMapper

(value) => Result<U, E>

Chaining (ignored)

Returns

Result<U, E>

Err with same error

See

andThenAsync for async version

Example

ts
Result.err('fail').andThen((x) => Result.ok(x * 2))
// Err("fail")

Result.err('fail').andThen((x) => Result.err('backup'))
// Err("fail") - keeps original error

Implementation of

ResultMethods.andThen


or()

or(result): Result<T, E>

Defined in: core/err.ts:508

Returns this Result or alternative.

For Err, returns the provided alternative Result.

Parameters

result

Result<T, E>

Alternative Result

Returns

Result<T, E>

The alternative Result

See

Example

ts
Result.err('fail').or(Result.ok(42))
// Ok(42)

Result.err('fail').or(Result.err('backup'))
// Err("backup")

Implementation of

ResultMethods.or


orElse()

orElse(onError): Result<T, E>

Defined in: core/err.ts:539

Returns this Result or executes error recovery.

For Err, executes recovery function with the error. Allows converting Err to Ok or generating new Err.

Parameters

onError

(error) => Result<T, E>

Recovery function

Returns

Result<T, E>

Result returned by recovery

See

Examples

ts
Result.err('not found').orElse((e) => Result.ok(null))
// Ok(null) - recovered

Result.err('fail').orElse((e) => Result.err('backup'))
// Err("backup") - error replaced
ts
// Fallback chain
fetchFromCache()
  .orElse(() => fetchFromDatabase())
  .orElse(() => fetchFromAPI())

Implementation of

ResultMethods.orElse


zip()

zip<U, E2>(result): Result<[T, U], E | E2>

Defined in: core/err.ts:557

Combines two Results into tuple (fails if any is Err).

Type Parameters

U

U

Second Result success type

E2

E2

Second Result error type

Parameters

result

Result<U, E2>

Result to combine (ignored)

Returns

Result<[T, U], E | E2>

Err with this error

See

and for chaining and discarding the first Ok value.

Example

ts
Result.err('fail').zip(Result.ok(2))
// Err("fail")

Implementation of

ResultMethods.zip

Checking

isErr()

isErr(): this is Err<E, Error>

Defined in: core/err.ts:66

Checks if this Result is the Err variant.

Returns

this is Err<E, Error>

Always true for Err

See

isOk for the opposite check

Example

ts
Result.err('fail').isErr() // true
Result.ok(42).isErr() // false

Implementation of

ResultMethods.isErr


isErrAnd()

isErrAnd(predicate): this is Err<E, Error>

Defined in: core/err.ts:105

Checks if it's Err and if the error satisfies a predicate.

Useful for filtering specific error types or conditions.

Parameters

predicate

(error) => boolean

Validation function

Returns

this is Err<E, Error>

true if Err and predicate passes

Examples

ts
const err = Result.err(new Error('not found'))
err.isErrAnd((e) => e.message.includes('not'))
// true
ts
// Checking specific error type
if (result.isErrAnd((e) => e.code === 404)) {
  console.log('Resource not found')
}

Implementation of

ResultMethods.isErrAnd


isOk()

isOk(): this is Ok<T, never>

Defined in: core/err.ts:51

Checks if this Result is the Ok variant.

Returns

this is Ok<T, never>

Always false for Err

See

isErr for the opposite check

Example

ts
Result.err('fail').isOk() // false

Implementation of

ResultMethods.isOk


isOkAnd()

isOkAnd(_predicate): this is Ok<T, never>

Defined in: core/err.ts:81

Checks if it's Ok and if the value satisfies a predicate.

Parameters

_predicate

(value) => boolean

Validation function (ignored)

Returns

this is Ok<T, never>

Always false for Err

See

isErrAnd for the opposite check

Example

ts
Result.err('fail').isOkAnd((x) => x > 5) // false

Implementation of

ResultMethods.isOkAnd

Conversion

toJSON()

toJSON(): object

Defined in: core/err.ts:757

Converts Result to JSON object.

Useful for serialization and APIs.

Returns

object

JSON representation

error

error: E

type

type: "err"

Example

ts
Result.err('fail').toJSON()
// { type: 'err', error: 'fail' }

JSON.stringify(Result.err('fail'))
// '{"type":"err","error":"fail"}'

Implementation of

ResultMethods.toJSON


toPromise()

toPromise(): Promise<never>

Defined in: core/err.ts:719

Converts Result to rejected Promise.

Returns

Promise<never>

Promise rejecting with the error

Examples

ts
try {
  await Result.err('fail').toPromise()
} catch (e) {
  console.log(e) // "fail"
}
ts
// Integrating with Promise-based code
Result.err('fail')
  .toPromise()
  .catch((e) => console.error(e))

Implementation of

ResultMethods.toPromise


toString()

toString(): string

Defined in: core/err.ts:737

Converts Result to string representation.

Returns

string

Format "Err(error)"

Example

ts
Result.err('fail').toString()
// "Err(fail)"

Result.err(new Error('oops')).toString()
// "Err(Error: oops)"

Implementation of

ResultMethods.toString

Inspecting

contains()

contains(_value, _comparator?): boolean

Defined in: core/err.ts:578

Checks if Ok contains specific value (always false for Err).

Parameters

_value

T

Value to compare (ignored)

_comparator?

(actual, expected) => boolean

Comparator (ignored)

Returns

boolean

Always false

Example

ts
Result.err('fail').contains(42) // false

Implementation of

ResultMethods.contains


containsErr()

containsErr(error, comparator?): boolean

Defined in: core/err.ts:610

Checks if Err contains specific error.

Uses strict equality (===) by default. Custom comparator allows checking complex objects.

Parameters

error

E

Error to compare

comparator?

(actual, expected) => boolean

Custom comparator

Returns

boolean

true if errors match

Examples

ts
Result.err('fail').containsErr('fail') // true
Result.err('fail').containsErr('other') // false
ts
// With objects (different references)
Result.err({ code: 500 }).containsErr({ code: 500 })
// false
ts
// With custom comparator
Result.err({ code: 500 }).containsErr(
  { code: 500 },
  (a, b) => a.code === b.code
)
// true

Implementation of

ResultMethods.containsErr


inspect()

inspect(_visitor): Result<T, E>

Defined in: core/err.ts:661

Performs side effect on success value (not applicable for Err).

Parameters

_visitor

(value) => void

Side effect (ignored)

Returns

Result<T, E>

This Err unchanged

See

Example

ts
Result.err('fail').inspect((x) => console.log(x))
// Err("fail") - nothing is executed

Implementation of

ResultMethods.inspect


inspectErr()

inspectErr(visitor): Result<T, E>

Defined in: core/err.ts:689

Performs side effect on error.

Useful for logging, metrics, or error debugging.

Parameters

visitor

(error) => void

Side effect function

Returns

Result<T, E>

This instance for chaining

See

inspect for value inspection

Examples

ts
Result.err('fail')
  .inspectErr((e) => console.error('Error:', e))
  .mapErr((e) => new Error(e))
// logs "Error: fail", returns Err(Error: fail)
ts
// Logging and monitoring
fetchUser(id)
  .inspectErr((error) => {
    logger.error('Failed to fetch user', { userId: id, error })
    metrics.increment('user.fetch.error')
  })

Implementation of

ResultMethods.inspectErr


match()

match<L, R>(handlers): L | R

Defined in: core/err.ts:644

Pattern matching on Result state.

Executes error handler for Err.

Type Parameters

L

L

Ok handler return type

R

R

Err handler return type

Parameters

handlers

Handlers

err

(error) => R

ok

(value) => L

Returns

L | R

Result from error handler

Examples

ts
const msg = Result.err('not found').match({
  ok: (x) => `Value: ${x}`,
  err: (e) => `Error: ${e}`
})
// "Error: not found"
ts
// Specific handling by error type
result.match({
  ok: (data) => processData(data),
  err: (error) => {
    if (error.code === 404) return showNotFound()
    if (error.code === 500) return showServerError()

    return showGenericError()
  }
})

Implementation of

ResultMethods.match

Transforming

filter()

Call Signature

filter(predicate): Result<T, Error>

Defined in: core/err.ts:399

Filters Ok value based on predicate (not applicable for Err).

Parameters
predicate

(value) => boolean

Validation function (ignored)

Returns

Result<T, Error>

This Err unchanged

See

isErrAnd for validation

Example
ts
Result.err('fail').filter((x) => x > 0)
// Err("fail")
Implementation of

ResultMethods.filter

Call Signature

filter(predicate, onReject): Result<T, E>

Defined in: core/err.ts:418

Filters Ok value with custom error (not applicable for Err).

Parameters
predicate

(value) => boolean

Validation (ignored)

onReject

(value) => E

Error generator (ignored)

Returns

Result<T, E>

This Err unchanged

See

isErrAnd for validation

Example
ts
Result.err('fail').filter(
  (x) => x > 0,
  (_x) => new Error('negative')
)
// Err("fail")
Implementation of

ResultMethods.filter


flatten()

flatten<U, E2>(this): Result<U, E | E2>

Defined in: core/err.ts:440

Flattens nested Result (not applicable for Err).

Type Parameters

U

U

Inner Result value type

E2

E2

Inner Result error type

Parameters

this

Err<Result<U, E2>, E>

Nested Result

Returns

Result<U, E | E2>

Flattened Err

Example

ts
Result.err('fail').flatten()
// Err("fail")

Implementation of

ResultMethods.flatten


map()

map<U>(_mapper): Result<U, E>

Defined in: core/err.ts:302

Transforms the success value (not applicable for Err).

For Err, keeps the error and only adjusts value type.

Type Parameters

U

U

Transformed value type

Parameters

_mapper

(value) => U

Transformation (ignored)

Returns

Result<U, E>

Err with same error, different value type

See

Examples

ts
Result.err('fail').map((x) => x * 2)
// Err("fail")
ts
// Chaining maps on error
Result.err('fail').map((x) => x * 2).map((x) => x + 1)
// Err("fail")

Implementation of

ResultMethods.map


mapErr()

mapErr<E2>(mapper): Result<T, E2>

Defined in: core/err.ts:382

Transforms the error.

Applies function to error and returns new Err with result. Useful for normalizing or enriching errors.

Type Parameters

E2

E2

New error type

Parameters

mapper

(error) => E2

Error transformer

Returns

Result<T, E2>

Err with transformed error

See

mapErrAsync for async version

Examples

ts
Result.err('not found')
  .mapErr((e) => new Error(e))
// Err(Error: not found)
ts
// Normalizing error types
result.mapErr((error) => ({
  code: error.code || 'UNKNOWN',
  message: error.message,
  timestamp: Date.now()
}))

Implementation of

ResultMethods.mapErr


mapOr()

mapOr<U>(_mapper, defaultValue): U

Defined in: core/err.ts:323

Transforms value or returns default.

For Err, ignores mapper and returns default.

Type Parameters

U

U

Transformed value type

Parameters

_mapper

(value) => U

Transformation (ignored)

defaultValue

U

Default value

Returns

U

The default value

See

Example

ts
Result.err('fail').mapOr((x) => x * 2, 42) // 42
Result.ok(5).mapOr((x) => x * 2, 42) // 10

Implementation of

ResultMethods.mapOr


mapOrElse()

mapOrElse<U>(_okMapper, errorMapper): U

Defined in: core/err.ts:353

Transforms value using appropriate mapper.

For Err, uses error mapper.

Type Parameters

U

U

Result type

Parameters

_okMapper

(value) => U

Success mapper (ignored)

errorMapper

(error) => U

Error mapper

Returns

U

Result from error mapper

See

mapOrElseAsync for async version

Examples

ts
Result.err('fail').mapOrElse(
  (x) => x * 2,
  (e) => -1
)
// -1
ts
// Converting error to valid value
const value = result.mapOrElse(
  (user) => user.name,
  (error) => 'Anonymous'
)

Implementation of

ResultMethods.mapOrElse