我已经在我正在处理的项目中实现了一个命令模式。这几乎是当前的结构:
public class Response
{
public bool Success { get; private set; }
public static Response CreateErrorResponse()
{
return new Response { Success = false };
}
}
public interface ICommand<T> where T : Response
{
Task<T> ExecuteAsync();
}
public abstract CommandBase : ICommand<T> where T: Response
{
protected abstract Uri BuildUrl();
protected abstract Task<T> HandleResponseAsync();
public async override Task<T> ExecuteAsync()
{
var url = BuildUrl();
var httpClient = new HttpClient();
var response = await httpClient.GetAsync(url);
return await HandleResponseAsync(response);
}
}
我想处理 HttpClient 可能引发的任何异常,所以我想将 CommandBase.ExecuteAsync 更改为类似这样的东西......
public async override Task<T> ExecuteAsync()
{
var url = BuildUrl();
var httpClient = new HttpClient();
try
{
var response = await httpClient.GetAsync(url);
return await HandleResponseAsync(response);
}
catch (HttpRequestException hex)
{
return Response.CreateErrorResponse(); // doesn't compile
}
}
我得到的编译错误是“无法将类型响应转换为异步返回类型 T”。我不能使用T.CreateErrorResponse()
,如本问题所述。
我该如何解决这个问题?
对downvoters 进行编辑:无论您是否同意在这样的库中捕获异常,问题仍然存在!