How should I handle expected errors? eg. "username already exists"

Posted by Pheter on Stack Overflow See other posts from Stack Overflow or by Pheter
Published on 2010-05-11T20:29:48Z Indexed on 2010/05/11 20:34 UTC
Read the original article Hit count: 209

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). 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?

© Stack Overflow or respective owner

Related posts about error

Related posts about architecture