0

I have a function returning an Either such as GetUserFromDb(int id).

If the database is offline, should I catch the error in the function and wrap it in a failure / Left case or should I let it bubble out as an exception as there is nothing I can do and it really is an exceptional situation?

gnat
  • 21,442
  • 29
  • 112
  • 288
  • Whether you should return a failure or throw an exception really depends on the culture of the language you are using (obviously the answer won't be the same for C# and Haskell). What is your context? – amon Dec 04 '13 at 12:59
  • We are using C# – Blair Davidson Dec 04 '13 at 13:02
  • 3
    I have a feeling this is going to be one of those things that comes down to opinion. I have some experience in both C# and Haskell, and while this approach works for Haskell, C# is _built_ with the expectation that exceptions get thrown and bubble upwards. It's how the entire standard library works for .NET. You might be meeting an unnecessary amount of resistance by adopting the `Either (Failure|Success)` route. – KChaloux Dec 04 '13 at 13:22
  • 2
    @amon: in C#, `Either` isn't idiomatic anyway, it is generally preferred to have a `bool TryGetUserFromDb(int id, out User user)` instead of `Option GetUserFromDb(int id)` or `Either GetUserFromDb(int id)`. So, in this particular case I wouldn't worry too much about being idiomatic. – Jörg W Mittag Dec 04 '13 at 14:33

1 Answers1

1

Really, it depends on your domain model. Why is it that you use an Either in the first place? Generally speaking, the fact that a record for a particular ID isn't found because the record doesn't exist, is a normal result but that the record isn't found because the DB doesn't exist is not. So, it certainly makes sense to treat the two cases differently, i.e. return an Either in the first case and throw an exception in the second.

Of course, in a distributed application or a mobile one, losing the DB connection might be normal. And when using the DB only as dumb storage and managing all relationships in your application, not finding a record that the app expects to be there is an exceptional situation. It all depends on context.

Jörg W Mittag
  • 101,921
  • 24
  • 218
  • 318