我正在嘗試將TryCatch在多個地方使用的異常處理轉換為通用方法。這里的目標是讓自定義方法將服務方法作為參數并將結果作為Customer對象返回。我正在使用async Task所以已經寫了一個基本ErrorHandling方法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); }}在上面的方法中,我想復制原始異步任務的功能,如下所示:[HttpPost("{custId}")][Authorize]public async Task<IActionResult> GetCustomer(int custId){ Models.Customer customer; try { customer = await _service.GetCustomer(custId); if(customer == null) { return BadRequest("Error retrieving customer"); } } catch (Exception e) { return StatusCode(500, e.Message); } return Ok(note);}修改我原來的方法以使用新的錯誤處理方法后[HttpPost("{custId}")][Authorize]public async Task<IActionResult> GetCustomer(int custId){ return ErrorHandlingWrapper<Models.Customer>(async () => await _service.GetCustomer(custId) );}使用上面的代碼我得到一個異常無法隱式轉換 System.Threading.Tasks.Task 類型以返回 IActionResult 類型?我不太確定我的方法是否正確?
1 回答

白板的微信
TA貢獻1883條經驗 獲得超3個贊
問題在于一些錯誤的返回類型和缺少async/的使用await。我重構了你的示例以 return 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)
);
}
- 1 回答
- 0 關注
- 127 瀏覽
添加回答
舉報
0/150
提交
取消