如何在具有 return 类型任务的方法中尝试捕获?

How to try-catch inside a method with a return type of Task?

我有以下方法(为简单起见缩写):

public Task CreateAsync(TUser user)
{
    using (var connection = new SqlConnection(_connection))
    {
        return Task.FromResult(connection.Execute("CreateUser", param, commandType: CommandType.StoredProcedure));
    }
 }

我想合并一个 try-catch block,这样我就可以记录任何潜在的 Sql 错误。

public Task CreateAsync(TUser user)
{
     var result = ???; // what is the return type here?
     try
     {
         result = FromResult(connection.Execute("CreateUser", param, commandType: CommandType.StoredProcedure));
      }
      catch(SqlException sqlEx)
      {
          // log error here
       }

      return result;
}

我想我不确定 Task 的 return 类型是什么?

您应该使用异步方法而不是 Task.FromResult。 我假设您正在使用 Dapper 或某种扩展 SqlConnection 的框架。 我不知道存储过程是什么returns。如果 return 值无关紧要,那么代码应该如下所示。

public async Task CreateAsync(TUser user)
{
     try
     {
         await connection.ExecuteAsync("CreateUser", param, commandType: CommandType.StoredProcedure);
     }
     catch(SqlException sqlEx)
     {
         // log error here
     }
}

如果它确实重要(布尔示例):

public async Task<bool> CreateAsync(TUser user)
{
     bool result;
     try
     {
        await connection.ExecuteAsync("CreateUser", param, commandType: CommandType.StoredProcedure);
        result = true;
     }
     catch(SqlException sqlEx)
     {
         // log error here
        result = false;
     }

     return result;
}