Refit: Question: How to make 404 return null?

Created on 26 Sep 2017  路  6Comments  路  Source: reactiveui/refit

I have a rest API that returns 404 if the record is not found. How do I make Refit return null instead of throwing an exception?

outdated

Most helpful comment

@Cheesebaron I'm not saying to return null or any case of error. I'm saying that 404 maps to null on some cases and it would be nice to have this directly. This is pretty much how DbContext.Find() or .SingleOrDefault() works.

Maybe we just have different views on this, but I think it's a good idea. The PR is there for analysis.

All 6 comments

You can't. Catch the exception

Is there any way I could implement this as a "filter" plugin, or an attribute on the method? The main reason to use Refit is it's simplicity. Once we're forced to add lots of code to each call to handle common things, it starts to lose it's value.

PR's are welcome. You could probably add a attribute like [NullOnException] or whatever.

However, I personally don't see how catching a valid exception is "loss of value".

Hi. It's not that "cathing an exception is a loss of value". It's the fact that I expect this to be the default behavior against any call to the API. Having to add a try/catch to every call ends up being too much boilerplate for this.

I'll see if I can add this as an attribute.

Thanks.

Why would you need to write that for each of the calls?

You could just wrap your stuff in a simple method:

async Task<(bool, T)> TryCallStuffAsync<T>(Func<Task<T>> whatever)
{
    try
    {
        var derp = whatever();
        var herp = await derp.ConfigureAwait(false);
        return (true, herp);
    }
    catch (Exception ex)
    {
        Logger.LogException(ex);
        return (false, default(T));
    }
}

or simpler:

async Task<T> TryCallStuffAsync<T>(Func<Task<T>> whatever)
{
    try
    {
        var derp = whatever();
        return await derp.ConfigureAwait(false);
    }
    catch (Exception ex)
    {
        Logger.LogException(ex);
        return default(T);
    }
}

Then invoke with:

TryCallStuffAsync(() => Derp());

Returning null instead of throwing the exception seems kind of silly to me as default behavior, because what does null then mean? No internet connection? Error in the call because you provided bogus values? Internal Server Error? Bad authentication? How the hell do you expect someone to figure that out by just returning null?

@Cheesebaron I'm not saying to return null or any case of error. I'm saying that 404 maps to null on some cases and it would be nice to have this directly. This is pretty much how DbContext.Find() or .SingleOrDefault() works.

Maybe we just have different views on this, but I think it's a good idea. The PR is there for analysis.

Was this page helpful?
0 / 5 - 0 ratings