How can I safely handle invalid requests for repos

2019-07-02 03:33发布

问题:

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;
}