Error codes are the problem, not the solution. You probably don’t realize it, but all that code you add to “handle errors” are just making the problem worse. And no matter how much more time you devote to “error checking,” you will never end up with a system that’s smart enough to keep itself error free.
So why do you keep trying? As it happens, there is a better way: just stop doing the error checking. Purge your system of the concept of “error” in the right way, in fact, and you’ll end up with an implementation that works better in nominal cases and gives you better insight and opportunity to regain control when something unexpected happens. Your code will be simpler, too. To get this right we’ll need to reformulate your thinking a little.
Let’s talk about software errors/exceptions and how you can craft better software by giving them appropriate design considerations. I’ve often found that developers, even experienced developers, don’t put much thought into the error objects that they produce.
1. Be specific :
When an exceptional situation occurs and you wish to throw an exception for that state, what type of error should you throw?
2. Great software error messages :
While that seems helpful, it is not a wise idea. Firstly, it leaks implementation details to any users who might see the error message. Secondly, there’s only so much context you can squeeze into the message.
3. Use error properties :
You can simply add properties to your implementation that states properties that matter to you.
4. Only use exceptions in exceptional cases :
This is more a general rule, but exceptions are supposed to be exceptional. They break control flow making it difficult to understand the repercussions of an exception. That means it can be hard for other developers to understand your code. Further making this worse, exceptions are often treated in special ways by the host runtime. Exceptions should be exceptional.