How can I safely handle invalid requests for repos

2019-07-02 03: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?

2条回答
疯言疯语
2楼-- · 2019-07-02 03:37

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;
}
查看更多
家丑人穷心不美
3楼-- · 2019-07-02 03:52

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..).

查看更多
登录 后发表回答