Custom Errors in Elm
module Main exposing (main)
import Html exposing (Html, text)
type alias ArgError =
{ arg : Int
, message : String
}
type Error
= CustomError ArgError
| OtherError String
f : Int -> Result Error Int
f arg =
if arg == 42 then
Err (CustomError { arg = arg, message = "can't work with it" })
else
Ok (arg + 3)
main : Html msg
main =
case f 42 of
Err (CustomError ae) ->
text <| String.fromInt ae.arg ++ " - " ++ ae.message
Err (OtherError msg) ->
text msg
Ok _ ->
text "No error occurred"
In Elm, we don’t have the concept of “custom errors” in the same way as Go, but we can achieve similar functionality using the Result
type and custom types for errors.
We define a custom type ArgError
to represent our specific error case:
type alias ArgError =
{ arg : Int
, message : String
}
We then create a union type Error
that can represent either our custom ArgError
or other types of errors:
type Error
= CustomError ArgError
| OtherError String
The f
function returns a Result Error Int
, which is Elm’s way of handling errors:
f : Int -> Result Error Int
f arg =
if arg == 42 then
Err (CustomError { arg = arg, message = "can't work with it" })
else
Ok (arg + 3)
In the main
function, we use pattern matching to handle the different possible outcomes:
main : Html msg
main =
case f 42 of
Err (CustomError ae) ->
text <| String.fromInt ae.arg ++ " - " ++ ae.message
Err (OtherError msg) ->
text msg
Ok _ ->
text "No error occurred"
This approach allows us to handle our custom error type specifically, while still accommodating other potential error types.
To run this Elm program, you would typically compile it to JavaScript and run it in a browser. The output would be:
42 - can't work with it
This example demonstrates how to implement custom error handling in Elm, which provides a type-safe way to deal with different error scenarios.