gpt4 book ai didi

java - 是否可以使用java方法返回 "if condition satisfies return a list else return an error message"

转载 作者:行者123 更新时间:2023-12-01 19:31:39 26 4
gpt4 key购买 nike

我知道在Java中一个方法只能返回一种返回类型...但是如果有任何可能,请告诉我。从下面的方法中,如果条件满足,我尝试返回一个列表,否则我尝试返回错误消息。

这是我的代码:

@RequestMapping(value = "/getcompanies", method = RequestMethod.POST)
public List<CompanyMaster> getCompanies(@RequestBody UserDetails user) {
String OrgLoginId = user.getOrgLoginId();
String password = user.getuPassword();
String checkLoginId = null;
String uPassword = null;
String encPassword = null;
String loginId = null;
String checkAuthorized = null;
// String loginId=userService.getLoginId(OrgLoginId);
List<Object[]> CheckIdPassword = userService.checkLoginId(OrgLoginId);
List<Object[]> results = CheckIdPassword;
for (Object[] obj : results) {
checkLoginId = obj[0].toString();
if (null == obj[1]) {
uPassword = "";
} else {
uPassword = obj[1].toString();
}
loginId = obj[2].toString();
}
checkAuthorized = loginId.substring(0, 3);
if (null != password) {
MD5 md5 = new MD5();
encPassword = md5.getPassword(password);
}
if (checkLoginId == null) {
return "Incorrect loginId..Please enter valid loginId";
} else if (encPassword.equals(uPassword)) {
if (checkAuthorized.equals("STE")) {
List<CompanyMaster> companyList = userService.getCompanyList(OrgLoginId);
return companyList;
} else {
return "You are not Authorized";
}
} else {
return "Incorrect Password";
}

最佳答案

是的,这是可能的,创建一个自定义异常,例如“MyAppException”,然后抛出该异常以及您想要的错误消息。

将逻辑写入 try{}catch block 中,并在 catch 中引发异常,以便响应包含错误消息

public List<CompanyMaster> getCompanies(@RequestBody UserDetails user) throws MyAppppException
{
try
{
//your logic which throws error
return companyList;
}
catch( final MyAppException we )
{
throw new MyAppException("User not found", HttpStatus.NOT_FOUND);
}
}

引用此链接 https://www.codejava.net/java-core/exception/how-to-create-custom-exceptions-in-java

关于java - 是否可以使用java方法返回 "if condition satisfies return a list else return an error message",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59622781/

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