MVC handles exception from child async method

How do I handle an exception from the thread of a child activity in MVC?

In this example, the exception from the MakePayment method is not handled by the catch of the caller:

Action in the controller:

public async Task<ActionResult> Payment()

        var tokenId = "12345";
        var order = new OrderViewModel
                        Amount = 10.00,
                        Description = "Widget",
                        Customer = 1                         

        var payment = new PaymentService();
        var model = await payment.MakeCharge(tokenId, order);

    catch(Exception ex)
        ViewBag.Message = ex.Message.toString();
        return view("Failed");

    return View(model);


Payment class:

public class PaymentService
  public async Task<Charge> MakeCharge(string tokenId, OrderViewModel order)
     return await Task.Run(() =>
       var myCharge = new ChargeCreateOptions
          Amount = order.Amount,
          Description = order.Description,
          TokenId = tokenId

       var chargeService = new ChargeService();
       var charge = chargeService.create(mycharge);    

       return charge;       



Thanks for any recommendations.


source to share

1 answer

I know this is an old question, but I don't support it yet as pointed out in the comments.

Apart from this boring answer, I suggest you read this article about the news in async try / catch methods included in C # 6.

Now I see no reason to use Task.Run()

in your example. An obvious example of when you should be using Task.Run()

is when you don't want to block the UI thread when running with a processor that is synchronous. In your case, you don't have a UI thread.



All Articles