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.

module Main where

import Prelude

import Data.Either (Either(..))
import Effect (Effect)
import Effect.Console (log)

-- A custom error type usually has the suffix "Error".
newtype ArgError = ArgError 
  { arg :: Int
  , message :: String
  }

-- Implementing the Error class for our custom error type
instance showArgError :: Show ArgError where
  show (ArgError e) = show e.arg <> " - " <> e.message

instance errorArgError :: Error ArgError where
  message (ArgError e) = e.message

-- Our function that might return an error
f :: Int -> Either ArgError Int
f arg = 
  if arg == 42
    then Left $ ArgError { arg, message: "can't work with it" }
    else Right $ arg + 3

main :: Effect Unit
main = do
  case f 42 of
    Left err -> do
      log $ "Error: " <> show err
    Right result -> 
      log $ "Result: " <> show result

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:

$ spago run
Error: 42 - can't work with it

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.