Error Handling — Returning Results

Michael Altmann
2 min readApr 19, 2017

--

If you google “error handling .net” or “error handling java” you get results about exceptions and exception handling. Therefore, many of us think using exceptions is the silver bullet for handling errors in modern .Net/Java applications. Yes, we could definitely use exceptions for application errors but I think we can do it in a much cleaner way.

The idea which is discussed in this article is initially introduced by Martin Fowler in 2004 in his article Notification.

Whats wrong with exceptions?

Exceptions are not completly wrong. In some of his articles (here and here) Vladimir Khorikov described in which cases exceptions should be used and in which cases not. I fully agree with his opinion, thus I try to summarize it. There are two types of errors.

  • First, there are errors, we don’t know how to deal with. This type of error represents unexpected bugs and should be handled by exceptions because we don’t know how to handle this case. The best option is to terminate the current operation.
  • Second, there are errors, we know how to deal with. These are expected error cases. For example validation errors or transient/recoverable software and hardware failures.

If you need help separating these two error types, read that. We skip the handling of the first error type, because it is not issue in this article.

Handling errors we know how to deal with

Okay, so we want to handle expected error cases we know how to deal with but without using exception handling. Any ideas? We could return a null object or false in case of failure but then we would lose a bunch of information concerning the reason of the failure. So a good solution (highly inspired by Martin Fowler and Vladimir Khorikov) is to return a Result object which indicates success or failure of an operation.

Here is some sample code:

The first method returns a Result object indicates success or failure. The second method — the client — checks the Result object and have to handle both cases, the error and the success case.

Pros

  • Clear program flow, no intransparent jumps from throw in a catch.
  • Make the used error handling mechanism explicit. Method signature shows the returning Result object. So from the client’s point of view the error handling mechanism is absolutely clear.
  • Returning more then one error is possible

Cons

  • The client have to manually check if the operation fails. If you use exception handling you have no chance to ignore an exception.
  • No built-in language support in C# or Java.

I built a small .Net library called “FluentResults” which provides a lightweight Result object. You can return multiple error or success messages. Each error can be designed as class and you can also describe the reasons or meta data of an error in an hierarchical way. Of course, returning a Result object with a value is also possible.

Links

--

--