What are some good ways to handle known errors that occur in a method?
Take the user registration method as an example. When a user logs in, the SignUp( User user ) method is SignUp( User user ) . Several known errors are known.
- Email is already registered
- Username already registered
- Etc
You can specify specific exceptions:
public void SignUp( User user ) {
Certain exceptions can now be detected.
This is bad, in my opinion, because exceptions are used to control the flow.
You can return a logical message if it was successful, and send an error message that will be set if an error occurs:
public bool SignUp( User user, out/ref string errorMessage ) {
I do not like this for several reasons.
- Value must be returned. What if the method should return a value?
- An error message should be transmitted at any time.
- The consumer of the method should be the one who determines what the message is.
Let me just say something where the actual message set in the method is bad.
You can use error codes:
public enum Errors { Successful = 0, EmailExists, UsernameExists, Etc } public Errors SignUp( User user ) {
The most recent of them is the one I like best, but I still don't like it. I don't like the idea of passing an error code. I also don't like the idea of returning the code, for that matter.
I like the idea of using custom exceptions because it seems a little cleaner, but I don't like the idea of using exceptions to control the flow. Perhaps in specific cases like this example, an email already in the system SHOULD be an exception, and that’s normal.
What have other people done in this situation?
Josh close
source share