如果在读取时存在IOException,如何返回500状态代码

Ren*_*nie 5 java exception-handling

说我有以下代码段

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
    }

}
Run Code Online (Sandbox Code Playgroud)

如果发生异常,我该如何处理错误?我想知道它发生了,并将500代码返回给用户.

我应该抛出异常并在其他类中捕获它吗?

是否有更优雅的方式来获得反馈?

Oll*_* Zi 1

您可以返回此类的实例:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

在你的情况下:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

以及 Result 类的缩写形式:)

public class Result {
    public boolean errorOccurs;
    public boolean isValid;
    public Exception exception;
}
Run Code Online (Sandbox Code Playgroud)