DEV Community

Type-Safe Error Handling In TypeScript

Gio on May 05, 2019

Originally posted on my blog We've all been there before. We write a function that has to deal with some edge case, and we use the throw keyword...
Collapse
 
stephenh profile image
Stephen Haberman

I think you have basically a good idea, but taking it to an extreme like this is not useful, IMO. I.e.:

Users of your API are not required to catch (the compiler
doesn't enforce it). This means you will eventually hit a
runtime error ... it's just a matter of time

True, but even with result ADTs, it's still just a matter of time, because runtime errors will always happen. You've changed your one "if not url, return the err result" line to not throw, but what about all of the code your function calls? I.e. you call randomNpmLibrary.whatever() or what not.

To literally never throw a runtime exception, you'd have to wrap your function implementation with a try catch:

try {
  ... regular code...
  if (boundaryCondition(...)) { return err(...);
  return result(...);
} catch (e) {
  return err(...); // something i called failed
}
Enter fullscreen mode Exit fullscreen mode

Anytime you call code (either yours or 3rd party) that a) hasn't moved over to the error ADT code style, or b) isn't 100% perfect in its adherence to the ADT code style and still accidentally NPEs/runtime exceptions when it isn't supposed to.

So, I think chasing "no runtime exceptions" is just a false/unattainable premise.

The other pitfall is that, if you want to represent "all failures return error instead of throw", eventually your ADT's error type expands and expands until they become super generic Result<Data | AnyError>. And you've lost any notion of the type-safety that you were after.

The reason is exactly what happened to checked exceptions; you start with Result<Data, DbError>. But now there is also an error if the user passes the wrong data, so you do Result<Data, DbError | ConfigError>. Now all your callers have to match on the new error (which we assert is good), or, they need to pass the new | ConfigError up to their callers, i.e. bubble up the error. So you're updating a lot of return values to do "oh right, add | ConfigError for my new error condition".

Which is exactly what happened with checked exceptions, having to add "oh right, also throws XyzException" all over your codebase whenever you discovered/added code for a new error condition.

So, to avoid updating all those places, maybe you make a more generic error type, like Result<Data, DataLayerError>, but now you need to convert all non-DataLayerErrors (like NoSuchMethod/etc.) into a DataLayerError, which is exactly like what ServiceLayerExceptions in checked exceptions did. :-)

Basically, at some point its actually a feature that "a random error can happen, it will blow up the stack, and you can catch it at some point on top".

Granted, for certain things, like network calls which are both extremely important and also almost certain to fail at some point, it makes a lot of sense to represent those as ADT return values, and force your caller to handle both success + networkerror. And so you're exactly right that it's a useful pattern to use there.

But I just wanted to point out that that I think taking it to the extreme of "my functions will never throw" and "I will use ADTs to represent any/all error conditions" is a slippery slope to a leaky abstraction, where Result<Data, Error> return values (i.e. its now very generic b/c it has to represent all failures, so how type-safe is it?) are doing essentially the same thing as catch but in a manner that is inconsistent and non-idiomatic with the runtime/rest of the ecosystem.

Collapse
 
architectophile profile image
architectophile • Edited

This is exactly what I was thinking reading this article. Is it really possible not to throw any errors? As long as you depend on any third-party libraries, there'll always be throw errors. Unless you completely control all of your codebase and they all follow your 'neverthrow' rules, you can't avoid some unexpected throw errors after all. So it's not an ideal method to handle typed errors.

Collapse
 
_gdelgado profile image
Gio

This is not true. I'm using neverthrow in production right now at the company that I work at.

You have to make a distinction between code that you wrote that you know won't throw, and code that others have written that you are not sure will throw or not.

For example, at my company, we use knex for database access. Knex is a huge library and determining in which circumstances it will throw or not is not worth anyones time. Instead, database operations have try/catch arms to catch errors from knex.

By wrapping this kind of code inside of try/catch you guarantee a typesafe interface to the consumers of your functions. Here's an example:

import { ok, err } from 'neverthrow'

const getWidget = async (widgetId: number): Promise<Result<Widget, DatabaseError>> => {
  try {
    const widget = await db('widgets').select('*').where('id', widgetId);

    return ok(widget)
  } catch (e) {
    return err(getDbError(e))
  }
}
Enter fullscreen mode Exit fullscreen mode

Now knex is being used in a typesafe way.

Thread Thread
 
architectophile profile image
architectophile • Edited

Okay. I got your point. So when you need to use a third-party library that might be throwable you wrap it inside of a try/catch statement and turn it into a neverthrow style module.
But what if one of your colleagues added a new feature that uses a new third-party library and forgot to wrap it inside of a try/catch statement?

For example,

import { makeHttpRequest } from './http-api.ts'
import { throwableMethod } from 'third-party-lib'

const run = async () => {
  const result = await makeHttpRequest('https://jsonplaceholder.typicode.com/todos/1')

  result
    .map(responseData => {
      // do something with the success value
      throwableMethod('this is a new feature')
    })
    .mapErr(errorInstance => {
      // do something with the failure value
    })
}

run()
Enter fullscreen mode Exit fullscreen mode

Wouldn't it lead to a more serious problem because inside your core codebase(like in your business rules) you don't have any try/catch statements than when you have some try/catch statements somewhere so the thrown errors will be caught at some point and you can handle it before it causes any serious problems?

Since at the beginning of your article you pointed out that "what if you or a colleague forget to wrap makeHttpRequest inside of a try / catch block.", I think that the same thing could happen even if you stick to use neverthrow style because when you use something new that you are not sure if is throwable or not, you must wrap it inside of a try/catch statement.

If there's something I got wrong, please let me know what I misunderstood.
Actually I admire your idea and work. I'm just curious if it's really resolving the core issues.

Thread Thread
 
_gdelgado profile image
Gio • Edited

But what if one of your colleagues added a new feature that uses a new third-party library and forgot to wrap it inside of a try/catch statement?

Yeah this definitely can occur. However, code review should prevent this sort of situation from happening too often. And it's ok. People make mistakes, no one's perfect. The team can retractively wrap the unsafe code in a try catch as part of their post-mortem.

This module isn't about creating the perfect codebase. Nor am I saying that you should never throw exceptions (how ironic). Strict adherence to dogma is never good!

What I am trying to say is this:

  • using throw as a control flow mechanism is suboptimal
  • modelling the various states of your functions (including whether your function could fail or not) within the type system leads to self-documenting code that is more obvious to others and easier to maintain

Wouldn't it lead to a more serious problem because inside your core codebase(like in your business rules) you don't have any ...

Hmm this depends at what depth the error is coming from and whether something higher up on the call stack does have a try / catch. The team needs to collectively agree to this sort of approach (hello coding guidelines!). This is more of a cultural / non-technical problem around enforcing a certain thing in your codebase.

Also, having a "catch all" try catch statement isn't really going to help you much. If you don't know what you're catching then you can't do much with it. So the counterargument in favor of having one catch statement at the top of your program is kind of irrelevant. All you can do is log the error? And maybe return a 500 to your users?

Collapse
 
karelkral profile image
Karel Kral

Thanks for your explanation, Stephen. Your words exactly describe my opinion.

Collapse
 
ybogomolov profile image
Yuriy Bogomolov

It is good to see that type-safe development is gaining popularity.
Your Result type is actually an Either monad. Your implementation, however, lacks a few goodies — like Bifunctor instance (allows mapping on Ok and Err simultaneously with a bimap method). Take a look at fp-ts package — there's a lot of other stuff Either can do :)

Collapse
 
_gdelgado profile image
Gio • Edited

Hey Yuriy,

Yup, it's the Either monad. But I intentionally omitted these terms (and others, such as "Algebraic Data Type") to show that functional programming can be practical and useful (not to say that it isn't).

The thing with Either is that it's really generic, and doesn't necessarily represent "the outcome of a computation that might fail". And although it's more convenient to others who are very familiar with functional programming, it adds to the slope of the learning curve (and makes functional programming seem again less practical).

I also chose to omit more useful APIs from the neverthrow package since simultaneous mapping can already be achieved through simpler means (using match), without having to teach people what a Bifunctor is. I took this approach because I am inspired by Elm's minimal design that tries to make functional programming as approachable and pragmatic as possible.

Collapse
 
jphilipstevens profile image
Jonathan Stevens

Beautiful!
As I read this I was thinking "hey Result is just an Either Monad"

Collapse
 
patroza profile image
Patrick Roza

The only thing I don’t like is that this brings us back to callbacks, which so elegantly got rid of with await.

Collapse
 
stealthmusic profile image
Jan Wedel

Would be great if typescript allows pattern matching, then you’ll do

with(result){
   Err(e) => console.log(“error!”);
   Ok(value) => console.log(value);
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
kip13 profile image
kip

Rust flavor here

Thread Thread
 
stealthmusic profile image
Jan Wedel

Yes, that's nice. There are a couple of functional languages that support it. E.g. Erlang where I first saw this in action.

Collapse
 
impurist profile image
Steven Holloway
Collapse
 
_gdelgado profile image
Gio

Maybe one day!

Thread Thread
 
stealthmusic profile image
Jan Wedel

Actually you can do something similar:

blog.logrocket.com/pattern-matchin...

It’s not as pretty as real pattern matching but it fits to this use car.

Collapse
 
patroza profile image
Patrick Roza • Edited

One way I was able to deal with 'callback hell':

  • Add functional helpers like map, mapErr, biMap (match), flatMap (andThen) etc that can work with both Result... and Promise<Result...
  • Add .pipe function on Ok and Err, and Promise, pretty much as implemented in rxjs: accept to pass N amount of continuation functions with signature: (previous) => next

so now I can:

await getSomeRecordsAsync() // => Promise<Result<SomeRecords, SomeError[]>>
  .pipe(
    map(someRecords => someRecords.map(x => x.someField).join(", ")), // => Promise<Result<string, SomeError[]>>
    mapErr(err => err.map(x => x.message).join(", ")), // => Promise<Result<string, string>>
    flatMap(saveStringAsync), // => Promise<Result<void, someError>>
    // etc
  )

(with full Typescript typing support btw!)

Thinking about releasing it to GitHub and npm at some point :)

Collapse
 
patroza profile image
Patrick Roza

My post, framework and sample just landed dev.to/patroza/result-composition-...

Collapse
 
airtucha profile image
Alexey Tukalo

Great article, and great lib. Thank you for spreading the concept of monadic error handling. I was also playing with it recently. I followed PromiseLike interface with my approach so, that it is actually possible to use async/await. I will be happy to hear your thoughts about it - npmjs.com/package/amonad

Collapse
 
_gdelgado profile image
Gio

Hey Alexey,

Thanks for the kind words :)

Note that neverthrow implements a promisible interface as well.

See the ResultAsync docs here

Collapse
 
airtucha profile image
Alexey Tukalo

Oh, it looks cool! What is an advantage of having ResultAsync as a separate abstraction?

Thread Thread
 
_gdelgado profile image
Gio

You can think of Result as eagerly evaluated and ResultAsync as lazily evaluated. They're two entirely different mechanisms and thus can't be merged into a single abstraction.

Collapse
 
juliang profile image
Julian Garamendy

Hi! Thanks for explaining how throw is not type safe. That was eye-opening!

The makeHttpRequest function on the example is async. That returns a Promise.

Why not simply reject the promise instead?

Collapse
 
_gdelgado profile image
Gio • Edited

Hey Julian,

Glad you enjoyed the article!

Well, using Promise.reject inside an async function is just an alternative to using throw.

Consider this example:

const doSomething = async () => Promise.reject(new Error('oh nooo'))

If you await on this function above, you will have to wrap it inside of a try / catch statement to prevent a runtime error. Further, there's no way you could encode the potential for failure into the above function. It's identical in behaviour to using throw ... So you lose all type safety.

Collapse
 
lukepuplett profile image
Luke Puplett • Edited

What's really going on is that your function is saying "The command failed successfully".

I've been coding for 35 years and have only just decided to properly learn TypeScript/JavaScript as opposed to occasional browser use. I'm normally a C# developer.

I'm a little confused because it feels like there isn't an accepted, idiomatic way to deal with errors, or perhaps new TS features are affording experiments in novel techniques such as this. And I see pushback against this idea, too.

I wonder if this is because it's not exactly error handling that's going on here.

The way I see it, there are exceptions and there are expected failures. "Exception" is a great term and in .NET we're told not to use them to communicate expected failures, because creating the call-stack is an expensive operation. They are exceptional.

An operation that is reasonably expected to fail, like a cache miss, or dereferencing a bad URL, or opening an since deleted file, should have its function designed to communicate this high likelihood of failure and also force the caller to deal with it. This is what this blog post is about.

In C# I might write a "Try" method that returns a boolean to indicate whether or not the successful object can be found in the out parameter (a variation for async would be to model that with a tuple).

public bool TryGet<T>(string key, out T result)

This isn't nearly as strong as what can be done with TypeScript (forcing callers to guard/narrow) but the idea is self-documentation.

Catching all the other less likely exceptions is out-of-scope for this "try" pattern. For example, at any time, a ThreadAbortException could be injected into the stack. Or an OutOfMemoryException can bubble up.

So you still have to add a try/catch, though generally you wouldn't catch an exception that you didn't have a robust way of handling; you'd let it bubble so as to give a caller much further up the stack a chance to catch and recover the situation or cause a bug that can be logged, experienced by a user and discussed.

In summary I think the neverthrow name is unfortunate for what is a great idea for a self-documenting failure mode pattern. I think the push back is because the name is setting up the wrong mental model in some people's minds.

I initially didn't like it, and then I realised, this is just "The command successfully failed". Thanks.

Collapse
 
bicatu profile image
Mario Bittencourt

Thank you for sharing. I liked the article although I have to process it further as it suggests that we should never throw an exception, which is quite strong :)

One thing that maybe is semantics (or not) is that in other languages we explicitly use the term exception to indicate that what happened was an exceptional situation(error). Anyone using Exceptions as a control follow in the same way of an if/else is already missing the mark.

So, saving to a db and getting a timeout is an exception while searching for something and not finding not.

Collapse
 
pianomanfrazier profile image
Ryan Frazier

Love this post. I have been writing a lot of Elm on side projects but use TypeScript at work. I recently encountered a big chunk of code that threw exceptions around. It was impossible to debug.

I found this post researching how I could refactor the code using Monads. Thanks.

Collapse
 
rugk profile image
rugk

This seems strongly inspired by Rust's type system. There, such a thing is built-in. It's Results all the way there…
And yeah, the syntax is very similar… (same names even)

Collapse
 
kip13 profile image
kip

Yes, i was thinking the same when i read it

Collapse
 
muhammedmoussa profile image
Moussa

i was have a bug happen only on production for a while and ignored, when you mentioned try and catch part at the beginning i found that exactly what causes the bug, thank you :D