Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Handle Errors with Elm’s Result Type

    Enrico BuonannoEnrico Buonanno

    The Result type represents the outcome of an operation that may result in an error.

    The documentation is available here. To follow along, get the Elm REPL. If you would like to try it out in your browser check out the Elm REPL here

    elmElm
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    00:00 Now if you want it to be more explicit about an error handling situation, then the result types is what you're after. So I'm showing maybe and result side by side so you can see how similar they are. With maybe, you have a single type parameter, a, that's the type of the value that is going to be wrapped in the just which is the successful case.

    00:22 If you look at result on the other hand, we have two type parameters, value, that's the inner value of the result in successful case which is called OK. In the failure case, which is called error, we have another value of a different type. The type which is also a generic parameter is called error.

    00:40 To demonstrate this, let me again start the Elm repo. Let me show you the signature for the string .2int function. This function takes a string and returns a result that is parameterized with the types string int.

    00:56 If you look at the definition of result here, the first type parameter is error. So in this case, string is being used to represent errors. On the other hand, the value parameter is now of type int which means that if the function succeed, then we get an OK with an int.

    01:13 Let me just demonstrate this. If I have a string, s1, and let this be the string one and if I now use the to int function to convert this to an int, then as you can see the result is an OK with the value one.

    01:29 On the other hand, let me now have an invalid value, s2. Let it be the string hello. If I try to use that with the to int function, you can see that we get an error with a payload of type string which says could not convert string hello to an int.

    Discuss

    Discuss