import * as resultJs from "https://deno.land/x/result_js@2.0.0/mod.ts";
Error handling with the Result
type.
Result<T,
| E> is the type used for returning and propagating errors.
It is an enum with the variants, Ok<T>
, representing success and containing a value, and Err<E>
, representing error and containing an error value.
Operators overview
Result
provides a wide variety of different operators.
Querying the variant
The isOk
and isErr
return true
if the Result
is Ok
or Err
, respectively.
Extracting contained values
Extract the contained value in a Result<T,
| E> when it is the Ok
. If the Result
is Err
:
expect
throws with a provided custom messageunwrap
throws with a generic messageunwrapOr
returns the provided default valueunwrapOrElse
returns the result of evaluating the provided function
Extract the contained value in a Result<T,
| E> when it is the Err
. If the Result
is Ok
:
Transforming contained values
Transforms the contained value of the Ok
:
map
transformsResult<T,
| E> intoResult<U,
| E> by applying the provided function to the contained value ofOk
and leavingErr
Transforms the contained value of the Err
:
mapErr
transformsResult<T,
| E> intoResult<T,
| F> by applying the provided function to the contained value ofErr
and leavingOk
Transform a Result<T,
| E> into a value of a possibly different type U
:
mapOr
applies the provided function to the contained value ofOk
, or returns the provided default value if theResult
isErr
mapOrElse
applies the provided function to the contained value ofOk
, or applies the provided default fallback function to the contained value ofErr
Logical operators
Treat the Result
as a boolean value, where Ok
acts like true
and Err
acts like false
.
The and
and or
take another Result
as input, and produce a Result
as output.
The and
can produce a Result<U,
| E> value having a different inner type U
than Result<T,
| E>.
The or
can produce a Result<T,
| F> value having a different error type F
than Result<T,
| E>.
name | result | input | output |
---|---|---|---|
and |
ok | result | result |
and |
err | result | err |
or |
ok | result | ok |
or |
err | result | result |
The andThen
and orElse
take a function as input, and only evaluate the function when they need to produce a new value.
The andThen
can produce a Result<U,
| E> value having a different inner type U
than Result<T,
| E>.
The orElse
can produce a Result<T,
| F> value having a different error type F
than Result<T,
| E>.
name | result | function input | function result | output |
---|---|---|---|---|
andThen |
Ok<T> |
T |
result | result |
andThen |
err | - | - | err |
orElse |
ok | - | - | ok |
orElse |
Err<E> |
E |
result | result |
Enums
The result type. |
Functions
f and | |
Returns the contained | |
Returns the contained | |
Returns | |
f isOk | Returns |
f map | |
Pattern matching for | |
f or | |
Returns the contained | |
Returns the contained | |
Returns the contained | |
Returns the contained |