亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

創建通用 try catch 任務方法時出現問題

創建通用 try catch 任務方法時出現問題

C#
搖曳的薔薇 2023-08-20 09:36:50
我正在嘗試將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)

                );

}


查看完整回答
反對 回復 2023-08-20
  • 1 回答
  • 0 關注
  • 127 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號