Tuesday, October 20, 2015

Error Handling patterns

So in my last job I talked to my team about patterns for error handling (4-5 years ago). I presented a series of patterns and I really did not have a strong opinion. So now I have a very strong opinion. Here are the patterns in pseudo code:

Style 1:
typeError foo(typeA p1, typeB p2, out typeReturn returnValue) {} 

Style 2:
typeReturn foo( typeA p1, typeB p2, out typeError errorValue) {}

Style 3:
typeReturn foo(typeA p1, typeB p2) throws typeError {}

At the time I had seen all three used and I wanted us to standardize although I didn't know which one was best. So the answer is that style 3 is best. Using the built in language feature that handles errors is best. Trying to keep your functions as close as possible to functional programming is best. Dividing your happy path code (in normal code) and your error path code (in catch blocks) makes it very clear. The ability for exceptions to flow up your call stack without intermediate handling by every intervening method is very useful. Also "out" parameters are a little questionable and aren't really as widely used as exceptions.

I work a lot with Promises and Promises also work much better with style 3. The other two styles are really a hold over from C days and that style has worked itself into languages that have better exception support. Should you do all your error handling with exceptions? No, if you can detect and resolve a problem locally do so, but for moving errors between stack frames, use style 3.

No comments:

Post a Comment