首页 > 解决方案 > 是否可以使用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";
    }

标签: java

解决方案


是的,它可能,创建一个自定义异常说“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


推荐阅读