C# Net Core 3.1返回一个包含异常详细信息的任务?

C# Net Core 3.1返回一个包含异常详细信息的任务?,c#,async-await,ado.net,task,asp.net-core-3.1,C#,Async Await,Ado.net,Task,Asp.net Core 3.1,我正在使用ADO.Net填充datatable,我已经将datatable填充方法放在一个单独的存储库中。我将存储库/接口注入到测试页面模型中。页面模型方法“OnPostUpdateAlarmDataTableAsync”需要调用接口并请求填充数据表。我希望返回填充此表的任务的结果,因此如果任务因任何原因失败,我可以在UI上通知用户,我还希望记录页面模型中错误的详细信息,因为这是调用线程 当前的编译错误是“无法将void赋值给隐式类型的变量”,但无论我尝试了什么样的代码更改组合,都无法正确编译。

我正在使用ADO.Net填充datatable,我已经将datatable填充方法放在一个单独的存储库中。我将存储库/接口注入到测试页面模型中。页面模型方法“OnPostUpdateAlarmDataTableAsync”需要调用接口并请求填充数据表。我希望返回填充此表的任务的结果,因此如果任务因任何原因失败,我可以在UI上通知用户,我还希望记录页面模型中错误的详细信息,因为这是调用线程

当前的编译错误是“无法将void赋值给隐式类型的变量”,但无论我尝试了什么样的代码更改组合,都无法正确编译。能够从异步操作返回包含异常细节的相关信息的任务是我想要实现的

接口:

public interface IAdoNetRepository
{
    Task FillAlarmsDataTable();
}
存储库:

public class AdoNetRepository : IAdoNetRepository
{
    public readonly IConfiguration _config;

    public AdoNetRepository(IConfiguration config)
    {
        _config = config;
    }

    // Used for method below GetUserGroupsData()
    public static SqlDataAdapter dataAdapter = new SqlDataAdapter();
    public static DataTable alarmDataTable;


    public async Task FillAlarmsDataTable()
    {
        string connectionString = _config.GetConnectionString("Data:DefaultConnection:ConnectionString");

        try
        {
            SqlConnection connection = new SqlConnection(connectionString);
            string cmdText1 = "SELECT * FROM [dbo].[Alarms] ORDER BY Name";

            // Create a new data adapter based on the specified query.
            dataAdapter = new SqlDataAdapter(cmdText1, connection);

            // Populate a new data table and bind it to the BindingSource.
            alarmDataTable = new DataTable
            {
                Locale = CultureInfo.InvariantCulture
            };
            await Task.Run(() => dataAdapter.Fill(alarmDataTable));
            //dataAdapter.Fill(alarmDataTable);

            return; // Return what ?
        }
        catch (Exception ex)
        {
            // Return the task with details of the exception
            return; // Return what?
        }
    }
}
页面模型:

public class TestModel : PageModel
{

    private readonly IAdoNetRepository _adoNetRepository;

    public TestModel(IAdoNetRepository adoNetRepository)
    {
        _adoNetRepository = adoNetRepository;
    }

    public async Task<IActionResult> OnPostUpdateAlarmDataTableAsync()
    {
        // This gets squiggly line compile error            
        var result = await _adoNetRepository.FillAlarmsDataTable();

        if (!result.Succeeded)
        {
            // log the exception returned from the task that failed!
        }

        return new JsonResult(result);
    }
}
公共类TestModel:PageModel
{
专用只读IAdoNetRepository(adoNetRepository);
公共测试模型(IAdoNetRepository adoNetRepository)
{
_adoNetRepository=adoNetRepository;
}
公共异步任务OnPostUpdateAlarmDataTableAsync()
{
//这将导致扭曲线编译错误
var result=await_adoNetRepository.FillAlarmsDataable();
如果(!result.successed)
{
//记录从失败的任务返回的异常!
}
返回新的JsonResult(result);
}
}

原始示例中的注释显示了您实际应该做什么

您需要创建一个模型来存储所需的信息

差不多

/// <summary>
/// Represents the result of an ADO.Net operation.
/// </summary>
public class AdoNetResult {
    private List<Exception> _errors = new List<Exception>();

    public bool Succeeded { get; protected set; }
    public IEnumerable<Exception> Errors => _errors;

    public static AdoNetResult Success { get; } = new AdoNetResult { Succeeded = true };
    public static AdoNetResult Failed(params Exception[] errors) {
        var result = new AdoNetResult { Succeeded = false };
        if (errors != null) {
            result._errors.AddRange(errors);
        }
        return result;
    }
}
捕获(捕获)正在使用的异常,并做出相应的响应

public async Task<IActionResult> OnPostUpdateAlarmDataTableAsync() {
    try {
        await _adoNetRepository.FillAlarmsDataTable();
        return Ok(); //200 OK
    catch(Exception ex) {
        //...log the exception returned from the task that failed!

        return new ExceptionResult(ex, includeErrorDetail:true);
    }
}
公共异步任务OnPostUpdateAlarmDataTableAsync(){ 试一试{ wait_adoNetRepository.FillAlarmsDataable(); 返回Ok();//200 Ok 捕获(例外情况除外){ //…记录从失败的任务返回的异常! 返回新的异常结果(例如,includeErrorDetail:true); } }
Hi Nkosi,非常感谢您的帮助,这真是太棒了:)
public async Task<AdoNetResult> FillAlarmsDataTable() {
    string connectionString = _config.GetConnectionString("Data:DefaultConnection:ConnectionString");

    try {
        SqlConnection connection = new SqlConnection(connectionString);
        string cmdText1 = "SELECT * FROM [dbo].[Alarms] ORDER BY Name";

        // Create a new data adapter based on the specified query.
        dataAdapter = new SqlDataAdapter(cmdText1, connection);

        // Populate a new data table and bind it to the BindingSource.
        alarmDataTable = new DataTable {
            Locale = CultureInfo.InvariantCulture
        };
        await Task.Run(() => dataAdapter.Fill(alarmDataTable));

        // Return what ?
        return AdoNetResult.Success; 
    } catch (Exception ex) {
        // Return the task with details of the exception
        return AdoNetResult.Failed(ex);
    }
}
public async Task<IActionResult> OnPostUpdateAlarmDataTableAsync() {

    var result = await _adoNetRepository.FillAlarmsDataTable();

    if (!result.Succeeded) {
        // log the exception returned from the task that failed!
        //result.Errors
    }

    return new JsonResult(result);
}
public Task FillAlarmsDataTable() {
    string connectionString = _config.GetConnectionString("Data:DefaultConnection:ConnectionString");

    SqlConnection connection = new SqlConnection(connectionString);
    string cmdText1 = "SELECT * FROM [dbo].[Alarms] ORDER BY Name";

    // Create a new data adapter based on the specified query.
    dataAdapter = new SqlDataAdapter(cmdText1, connection);

    // Populate a new data table and bind it to the BindingSource.
    alarmDataTable = new DataTable {
        Locale = CultureInfo.InvariantCulture
    };
    return Task.Run(() => dataAdapter.Fill(alarmDataTable));
}
public async Task<IActionResult> OnPostUpdateAlarmDataTableAsync() {
    try {
        await _adoNetRepository.FillAlarmsDataTable();
        return Ok(); //200 OK
    catch(Exception ex) {
        //...log the exception returned from the task that failed!

        return new ExceptionResult(ex, includeErrorDetail:true);
    }
}