How should I do error handling?

In my last post I told you not to do generic error handling.

The natural next question is then "How should I do error handling?".

That question can be hard to answer, and as always in software development the answer is: "It depends".

First of all error handling in every language is different, and you should certainly do what is idiomatic in your specific programming language.

Next it depends very much on you business case.

By making exception handling generic, you make error handling a technical thing - solved with technical methods and a technical mindset.

However when you do error handling you are, most likely, implementing something useful for the business you work for (if not you should probably stop and see why not). So we have to consider what the business needs us to do. If for instance you have a locked resource and your auth. system is down - do you give access to every one of do you shut out everyone? That is certainly not a technical question - somebody from the business side of things should be asked about that.

In the error handling, I mentioned in the last post, I btw. didn't find the error handling obvious: it took me a while to find out where the error handling was taking place.

The reason for this is, apart from my slowness, that the error handling did not stand out.

Error handling is the special case, and for a long time I tried to hide away the error handling, thinking that I did not want the special case (error handling) to stand in the way of the normal case.

However I have changed my mind on this.

For instance in go, error handling, done idiomatically, is every method that should be handled, returning a tuple of an error (if present) and the normal case return value. For every method call you have to check if the method succeed. When I first came to go - I hated it - but now I can see that at least error handling is in your face - you can see what is going on.

f, err := os.Open("/test.txt")
if err != nil {
fmt.Println(f.Name(), "opened successfully")

Bottom line:

Error handling is not a technical thing, but a business decision.

Error handling should be easily identifiable in the code, so you can see what is the normal case and what is the special case.

You might want to read the blog post I made about exception handling for junior developers.