Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question

marked as duplicate by gnat, Bart van Ingen Schenau, Kilian Foth, GlenH7, ChrisF Dec 7 '13 at 13:47

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

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 4 '13 at 12:59
We are using C# –  Blair Davidson Dec 4 '13 at 13:02
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 4 '13 at 13:22
@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<User> GetUserFromDb(int id) or Either<ErrorEnum, User> GetUserFromDb(int id). So, in this particular case I wouldn't worry too much about being idiomatic. –  Jörg W Mittag Dec 4 '13 at 14:33

1 Answer 1

up vote 0 down vote accepted

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.

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.