How can I safely handle invalid requests for repository data?

眉间皱痕 提交于 2020-01-14 19:42:09

问题


With this code:

public String Get(int id)
{
        return platypi.Find(p => p.Id == id).Name;
}

...I can get existing data via:

http://localhost:33181/api/DPlatypus/N

(where N corresponds to an existing ID). If I use a nonexistent value, though, it blows up.

So, I tried this:

public String Get(int id)
{
    if (!string.IsNullOrEmpty(platypi.Find(p => p.Id == id).Name))
    {
        return platypi.Find(p => p.Id == id).Name;
    }
    return string.Empty;
}

...but it has no beneficial effect. Is there a way to safely ignore invalid requests?


回答1:


You should be much more defensive than that. Check for null first.. otherwise you're asking for it to blow up:

var entity = platypi.Find(p => p.Id == id);

return entity == null ? string.Empty : entity.Name;

You're also currently doing more than a single lookup.. which you don't need (Find to check name.. then Find to return name..).




回答2:


If the Find method is raising an exception, you could wrap this in an exception handler. That would allow you to "safely" return an empty string on invalid input.

If Find returns null, you could do:

public String Get(int id)
{
    var item = platypi.Find(p => p.Id == id);

    return item == null ? string.Empty : item.Name;
}


来源:https://stackoverflow.com/questions/21125722/how-can-i-safely-handle-invalid-requests-for-repository-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!