为了账号安全,请及时绑定邮箱和手机立即绑定

创建通用 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 关注
  • 69 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信