Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/263.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 创建泛型try-catch任务方法时出现问题_C#_Asp.net Core_Try Catch - Fatal编程技术网

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