简体   繁体   中英

Method to handle exceptions in a async block to cannot convert return object to to async method return type

I have implemented a method to handle exceptions around a async block like below:

public async Task<ServiceResponse<T>> RetryTest<T>(Func<Task<ServiceResponse<T>>> method)
    {
        try
        {
            return await method.Invoke();
        }
        catch (Exception exception)
        {
            return FormatExceptionResponse<T>(exception);
        }
    }

And use it to wrap async code like:

public async Task<ServiceResponse<DataJob>> Insert(DataJob entity)
    {

        return await RetryTest<ServiceResponse<DataJob>>(async () =>
        {
            Context.AddObject("DataJobs", entity);
            DataServiceResponse responses = await Context.SaveChangesAsync();

            return new ServiceResponse<DataJob>((HttpStatusCode)responses.Last().StatusCode, entity);

        });

    }

However the last return statement has an error: Cannot convert expression type ServiceResponse to async method return type ServiceResponse.

Any clue how to fix this?

Your definition of RetryTest accepts a T and then returns a ServiceResponse<T>

When you call it you've supplied: ServiceResponse<DataJob> as T , so the return type of RetryTest , since it needs to wrap T in a ServiceResponse , should return a ServiceResponse<ServiceResponse<DataJob>> rather than a ServiceResponse<DataJob> . (You're not returning that, hence the error.)

You simply want to pass DataJob as the generic argument to RetryTest instead of ServiceResponse<DataJob> .

Or, better yet, just remove the generic arguments entirely when calling RetryTest and let them be inferred properly, and then you can't mess it up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM