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?
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;
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With