I am struggling to understand how I should design the error handling parts of my code. I recently asked a similar question about how I should go about returning server error codes to the user, eg. 404 errors. I learnt that I should handle the error from within the current part of the application; seem's simple enough.
However, what should I do when I can't handle the error from the current link in the chain? For example, I may have a class that is used to manage authentication. One of it's methods could be createUser($username, $password)
. Edit: This method will return a user id or user object. Within that function, I need to determine if the username already exists. If this is true, how should I alert the calling code about this? Returning null instead of a user object is one way. But how do I then know what caused the error?
How should I handle errors in such a way that calling code can easily find out what caused the error? Is there a design pattern commonly used for this kind of situation?
Edit: I forgot to mention: I am using PHP.
Solved: While many people argue that exceptions should not be used in this situation, I have come to the conclusion that it is the best solution.
Firstly, there is no simple, elegant alternative to exceptions. (I recon that it is not possible without a system built into the language... exceptions are already built in.)
Secondly, in response to the "exceptions should only be used for exceptional situations, and this is not one" argument: "When I call getFoo(), I actually expect to get a Foo. If I don't get it, it's by definition an exceptional event." (via, pkainulainen)