Custom Errors in PureScript
Our first example demonstrates how to create custom errors in PureScript. We’ll create a custom error type and implement the Error
class for it.
In this example, we define a custom error type ArgError
that contains an integer argument and an error message. We implement the Show
and Error
typeclasses for ArgError
, which is similar to implementing the Error()
method in Go.
The f
function demonstrates how to return our custom error. If the input is 42, it returns a Left
value containing our custom error. Otherwise, it returns a Right
value with the result.
In the main
function, we call f
with the argument 42 and pattern match on the result. If it’s a Left
(indicating an error), we print the error. Otherwise, we print the result.
To run this program, save it as Main.purs
and use the PureScript compiler and runtime:
This example shows how to create and use custom error types in PureScript, which provides a type-safe way to handle specific error conditions in your code.