简体   繁体   English

处理异步块中的异常的方法无法将返回对象转换为异步方法返回类型

[英]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. 但是,最后一个return语句有一个错误:无法将表达式类型ServiceResponse转换为异步方法返回类型ServiceResponse。

Any clue how to fix this? 任何线索如何解决这个问题?

Your definition of RetryTest accepts a T and then returns a ServiceResponse<T> 您对RetryTest定义接受一个T ,然后返回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> . 调用它时,您提供了: ServiceResponse<DataJob>作为T ,因此RetryTest的返回类型需要将T包装在ServiceResponse ,因此应返回ServiceResponse<ServiceResponse<DataJob>>而不是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> . 您只想将DataJob作为通用参数传递给RetryTest而不是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. 或者,更好的是,只需在调用RetryTest时完全删除泛型参数,然后正确推断出它们,然后您就可以将其弄乱。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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