ErrorTypes.jl
ErrorTypes provides an easy way to efficiently encode error states in return types. Its types are modelled after Rust's Option
and Result
.
Example
using ErrorTypes
function safe_maximum(x::AbstractArray)::Option{eltype(x)}
isempty(x) ? none : some(maximum(x))
end
function using_safe_maximum(x)
maybe = safe_maximum(x)
println(unwrap_or(and_then(y -> "Maximum is: $y", String, maybe), "ERROR: EMPTY ARRAY"))
end
See also: Usage
Advantages
- Zero-cost: In fully type-stable code, error handling using ErrorTypes is as fast as a manual check for the edge case, and significantly faster than exception handling.
- Increased safety: ErrorTypes is designed to make you not guess. By making edge cases explicit, your code will be more reliable for yourself and for others.
See also: Why use ErrorTypes?
Comparisons to other packages
The idea behind this package is well known and used in other languages, e.g. Rust and the functional languages (Clojure, Haskell etc). It is also implemented in the Julia packages Expect
and ResultTypes
, and to some extent MLStyle
. Compared to these packages, ErrorTypes offer:
- Efficiency: All ErrorTypes methods and types should be maximally efficient. For example, an
Option{T}
is as lightweight as aUnion{T, Nothing}
, and manipulation of theOption
is as efficient as a===
check againstnothing
. - Increased comfort. The main disadvantage of using these packages is the increased friction in development. ErrorTypes provides more quality-of-life functionality for working with error types than
Expect
andResultTypes
, for example the simpleOption
type. - Flexibility. Whereas
Expect
andResultTypes
require your error state to be encoded in anException
object, ErrorTypes allow you to store it how you want. Want to store error codes as aBool
? Sure, why not. - Strictness: ErrorTypes tries hard to not guess what you're doing. Error types with concrete values cannot be converted to another concrete error type, and non-error types are never implicitly converted to error types. Generally, ErrorTypes tries to minimize room for error.