KJSR
KJSR

Reputation: 1757

Issue creating a generic try catch task method

I am trying to convert my TryCatch exception handling used in multiple places to a generic method.

Aim here is for the custom method to take service method as parameter and return the result as Customer object.

I am using async Task so have written a basic ErrorHandling method as such

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

In the above method I want to replicate what my original async Task does as shown below:

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

After modifying my original method to use the new error handling method

[HttpPost("{custId}")]
[Authorize]
public async Task<IActionResult> GetCustomer(int custId)
{
     return ErrorHandlingWrapper<Models.Customer>(async () => 
                                await _service.GetCustomer(custId)
                );
}

With the above code am getting an exception

Cannot implicitly convert type System.Threading.Tasks.Task To return type IActionResult?

I am not really sure if my approach is correct?

Update

Customer.cs

public class Customer{
    public int CustId { get; set; }
    public string FirtName { get; set; }
    public string LastName { get; set; }
}

Upvotes: 1

Views: 942

Answers (1)

Patrick Hofman
Patrick Hofman

Reputation: 156988

The problem is with some wrong return types and the missing use of async/await. I refactored your example to return IActionResult. This should do:

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

Upvotes: 1

Related Questions