java - 是否可以使用java方法返回“如果条件满足返回列表,否则返回错误消息”
问题描述
我知道在 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 块中编写您的逻辑并在 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
推荐阅读
- php - 如何通过阅读 PDF 文件获得的 JSON 对象发送二进制数据?
- python-3.x - python中的Prime Checker
- javascript - 我正在做一个计算器,我想问如何编写乘法按钮
- javascript - Firestore - 对象未正确更新
- angular - 如何更改primeng切换按钮Angular中的标签?
- php - $.post() 无法传递数据
- bash - 如何在Shell脚本中删除从特定索引字符开始的所有字符
- python - 如何将数据框的列转换为不同长度的列表?
- apache-camel - apache camel可以支持电信直径吗?
- swift - 使用颤振的 iPhone XS ideviceinstaller 需要 UDID 验证 - 它不再是 40 位数字并且有破折号