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?
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
returnsnull
, you could do:You should be much more defensive than that. Check for
null
first.. otherwise you're asking for it to blow up:You're also currently doing more than a single lookup.. which you don't need (
Find
to check name.. thenFind
to return name..).