#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2005
    Posts
    415
    Rep Power
    20

    Error handling in OOP


    Hi,
    What is a good way to handle errors in classes that need to be re-usable in other projects.

    For example: I have a UserManager class with a login() method. Now several errors can happen in that method, including:
    - Given username does not exist
    - Password is incorrect
    - failed to setup a connection to the database

    I want the caller of the login() method of my class to be able to distinguish between the different errors. For example so that it can print a different message depending on whether the username or password was incorrect.

    Now I can do it like below, but then you just have the error message available, I am not able to test which error actually happened.
    PHP Code:
    class DatabaseCommunicator{
        
            function 
    UserManager(){

            }


            function 
    login$user$password ){
                if( ! 
    userExists$user ) ){
                    throw new 
    Exception("Username is not valid!");
                } else if( ! 
    userHasPassword$user$password ) ){
                    throw new 
    Exception("Password is not valid!")
                }
                
    // ...

            
    }
        } 
    And then use it like this:
    PHP Code:
        try{
            
    $um = new UserManager();
            
    $um->login("username""password")
        } catch( 
    Exception $e ){
            echo 
    $e;
        } 
    Now I could use custom exceptions, but then I have to make a custom exception for each error that can occur in the class right? And it also means the caller of the method needs to catch all these exceptions seperately.

    Also do you put a try/catch block around each method call that occur within a method or do you generally put a try/catch block around an entire method?

    If you have any other tips or suggestions feel free to tell me.

    Thanks in advance,
    Stefan1
  2. #2
  3. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,903
    Rep Power
    1045
    Hi,

    never tell your visitors if a certain account exists or not. This makes it easy for an attacker to collect valid accounts for an attack. It also violates the privacy of your users in case the username contains sensitive data (like the email address), because now you've made this data public to the whole world.

    There's only two types of error messages you may display: "The login credentials are incorrect" and "There was a technical issue". You do not expose any other information.

    It's also not a good idea to misuse exceptions for user feedback. Exceptions are for application errors. People entering invalid data is not exceptional, it's perfectly normal. In your case, you'd simply validate the data and collect all error messages in an array or something.

    Catching exceptions is generally very rare. You only do this if you actually wanna recover from an application error. You do not catch exceptions in order to display their message. That's a misunderstanding of the concept. Exceptions have been invented so that error handling can be delegated: If a method cannot handle an error, it's supposed to let it "bubble up" to the next higher method. If this method cannot handle it either, it again lets it "bubble up" and so on. If no method is able to handle the error, then the application stops and sends the error message to the right device.

    In your case, you probably don't need any exceptions at all. As a rule of thumb: When you find yourself writing lots of try-catch statements, you might be doing it wrong.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2005
    Posts
    415
    Rep Power
    20
    Thanks alot for your reply! I thought there must be a reason why most sites don't let you know if it was the username or password that was incorrect, so now I know.

    Ok so you don't throw exceptions for bad user input. But lets take another example. Consider an application that lets users play chess against eachother. There's an object for managing games (ie. create a game, join a game, make a move, etc).

    Now a user has created a game and is waiting for an opponent to join. Another user tries to join that game which is done with the method joinGame(). However, a number of things need to be checked in order to join a game:
    - The game must still be waiting for a player to join
    - You cannot join a game that you have created.
    - You cannot join a game if your chess-rating is not appropriate.

    When one of these conditions is not fulfilled, the joining of the game fails and the method must return or do something in order for the calling method to react differently depending on what went wrong. For example if the game is not waiting for a player to join anymore (because someone has join in the meanwhile), then you want to refresh the user's gamelist. If the chess rating of the game was not appropriate you might want to suggest to the user to change the filter for the joinable game list.

    What would be a good way of making the calling method aware of what kind of problems can occur? Just returning an int indicating the problem. (1=game is not joinable, 2=inappropriate chess rating etc). And what if the calling method wants pass this information to his caller again. Then you need to work with those error codes in many different objects.

    Is there a better way of handling this?

    Thanks again!

IMN logo majestic logo threadwatch logo seochat tools logo