C# 创建泛型try-catch任务方法时出现问题
我正在尝试将我在多个位置使用的C# 创建泛型try-catch任务方法时出现问题,c#,asp.net-core,try-catch,C#,Asp.net Core,Try Catch,我正在尝试将我在多个位置使用的TryCatch异常处理转换为通用方法 这里的目的是让定制方法将服务方法作为参数,并将结果作为Customer对象返回 我使用的是async任务,因此我编写了一个基本的错误处理方法 public Task<T> ErrorHandlingWrapper<T>(Func<Task<T>> action) { try { return action(); //return O
TryCatch
异常处理转换为通用方法
这里的目的是让定制方法将服务方法作为参数,并将结果作为Customer
对象返回
我使用的是async
任务
,因此我编写了一个基本的错误处理方法
public Task<T> ErrorHandlingWrapper<T>(Func<Task<T>> action)
{
try
{
return action();
//return Ok(action());
}
catch (Exception ex)
{
throw new Exception(ex.Message);
//return StatusCode(500, e.Message);
}
}
问题在于一些错误的返回类型以及缺少使用async
/wait
。我重构了您的示例以返回IActionResult
。这应该做到:
public async Task<IActionResult> ErrorHandlingWrapper<T>(Func<Task<T>> action)
{
try
{
//return action();
return Ok(await action());
}
catch (Exception ex)
{
//throw new Exception(ex.Message);
return StatusCode(500, ex.Message);
}
}
[HttpPost("{custId}")]
[Authorize]
public async Task<IActionResult> GetCustomer(int custId)
{
return await ErrorHandlingWrapper(async () =>
await _service.GetCustomer(custId)
);
}
public异步任务ErrorHandlingWrapper(Func操作)
{
尝试
{
//返回动作();
返回Ok(等待操作());
}
捕获(例外情况除外)
{
//抛出新异常(例如消息);
返回状态码(500,例如消息);
}
}
[HttpPost(“{custId}”)]
[授权]
公共异步任务GetCustomer(int-custId)
{
返回等待ErrorHandlingWrapper(异步()=>
等待服务。获取客户(客户ID)
);
}
[HttpPost("{custId}")]
[Authorize]
public async Task<IActionResult> GetCustomer(int custId)
{
return ErrorHandlingWrapper<Models.Customer>(async () =>
await _service.GetCustomer(custId)
);
}
public class Customer{
public int CustId { get; set; }
public string FirtName { get; set; }
public string LastName { get; set; }
}
public async Task<IActionResult> ErrorHandlingWrapper<T>(Func<Task<T>> action)
{
try
{
//return action();
return Ok(await action());
}
catch (Exception ex)
{
//throw new Exception(ex.Message);
return StatusCode(500, ex.Message);
}
}
[HttpPost("{custId}")]
[Authorize]
public async Task<IActionResult> GetCustomer(int custId)
{
return await ErrorHandlingWrapper(async () =>
await _service.GetCustomer(custId)
);
}