Reputation: 491
How to handle an exception from the thread of a child action in MVC?
In this example an exception from the MakePayment method is not handled by the catch of the calling action:
Action in controller:
public async Task<ActionResult> Payment()
{
try
{
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;
});
}
}
Thank you for any guidance.
Upvotes: 3
Views: 857
Reputation: 2376
I know this is an old question but I for the time being there is no support for this as stated in the comments.
Apart from that boring answer I suggest that you read this article https://msdn.microsoft.com/hu-hu/magazine/dn683793(en-us).aspx about the news in try/catch async methods coming in c#6.
Now I don't see any reason to use Task.Run()
in your example. An obvious example for when you should use Task.Run()
is when you don't want to block you UI-thread when doing CPU-heavy work that's synchronous. In your case you don't have any UI-thread.
Upvotes: 1