Ever wanted to use exceptions in Gleam? Now you can!
gexcept is a gleam library that provides exception handling in Gleam. It is build to be as generic as
possible as to not interfer with any existing type systems. It works for both Erlang and JavaScript targets.
To add gexecpt to your project, use the following command.
gleam add gexceptThe library provides two primary functions:
throw()to throw an exception, andtry()for catching and handling them.
Additionally, it includes functions for dealing with Result and Option instances. For more details, please
refer to the documentation.
Here's a basic example - you can find some more in test/gexcept_test.gleam.
import gexcept
import gleam/io
pub fn main() {
gexcept.try(
fn() {
gexpect.throw("exception")
"return value"
},
fn(exception) {
"caught: " <> exception
}
)
|> io.println
}For further documentation see /docs.
Because it is possible.
It undermines the core design principles of Gleam.
Building exceptions into your project will cause you more problems than it will solve (if it solves any problems at all).
So, please, never ever use this package.
The exceptions themselves are not type-checked, and there is no easy way to achive that.
Calling throw() without a surrounding try()-call will probably crash the program, but I consider this
undefined behaviour.
You can run the test suite using these commands.
gleam test --target=erlang
gleam test --target=javascript