Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a 500 status code if there is an IOException while reading

Say I have the following snippet

public boolean checkListing() {

    try {

        // open the users.txt file
        BufferedReader br = new BufferedReader(new FileReader("users.txt"));

        String line = null;
        while ((line = br.readLine()) != null) {
            String[] values = line.split(" ");
            // only interested for duplicate usernames
            if (username.equals(values[0])) {
                return true;
            }
        }
        br.close();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        // what to do here
    }

}

How should I handle the error if an exception occurs? I want to know that it happened and return a 500 code back to the user.

Should I throw and exception and catch it in the other class?

Is there a more elegant way to get feedback on it?

like image 493
Rentonie Avatar asked Nov 09 '22 15:11

Rentonie


1 Answers

You can return an instance of this class:

public class Result {

    private boolean errorOccurs;
    private boolean isValid;
    private Exception exception;

    public Result(boolean isValid){
        this(isValid, false, null);
    }

    public Result(boolean isValid, boolean errorOccurs, Exception exception){
        this.isValid = isValid;
        this.errorOccurs = errorOccurs;
        this.exception = exception;
    }

    public boolean isValid(){
        return isValid;
    }

    public boolean errorOccurs(){
        return errorOccurs;
    }

    public Exception getException(){
        return exception;
    }
}

In your case:

public Result checkListing() {

    try {

        // open the users.txt file
        BufferedReader br = new BufferedReader(new FileReader("users.txt"));

        String line = null;
        while ((line = br.readLine()) != null) {
            String[] values = line.split(" ");
            // only interested for duplicate usernames
            if (username.equals(values[0])) {
                return new Result(true);
            }
        }
        br.close();
        return new Result(false);
    } catch (IOException e) {
        e.printStackTrace();
        return new Result(false, true, e);
    }
}

And the short form of the Result class:)

public class Result {
    public boolean errorOccurs;
    public boolean isValid;
    public Exception exception;
}
like image 94
Olli Zi Avatar answered Nov 14 '22 22:11

Olli Zi