gpt4 book ai didi

java - 如果读取时出现 IOException,如何返回 500 状态码

转载 作者:搜寻专家 更新时间:2023-10-31 20:33:45 25 4
gpt4 key购买 nike

假设我有以下片段

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
}

}

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

我应该抛出异常并在另一个类中捕获它吗?

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

最佳答案

你可以返回这个类的一个实例:

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;
}
}

在你的情况下:

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);
}
}

以及 Result 类的缩写形式:)

public class Result {
public boolean errorOccurs;
public boolean isValid;
public Exception exception;
}

关于java - 如果读取时出现 IOException,如何返回 500 状态码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29705033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com