gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:38:24 26 4
gpt4 key购买 nike

我正在使用 ADO.Net 来填充数据表,我已将数据表填充方法放入单独的存储库中。我将存储库/接口(interface)注入(inject)到测试页面模型中。页面模型方法“OnPostUpdateAlarmDataTableAsync”需要调用接口(interface),请求填充数据表。我想从填充此表的任务中返回结果,因此如果任务因任何原因而失败,我可以在 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);
}
}

最佳答案

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

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

就像是

/// <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;
}
}

然而,接口(interface)需要重构
public interface IAdoNetRepository {
Task<AdoNetResult> FillAlarmsDataTable();
}

和实现
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);
}

另一种方法是让 FillAlarmsDataTable抛出它可能遇到的任何异常
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);
}
}

关于c# - Net Core 3.1 返回一个包含异常详细信息的任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60048630/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com