C#当类型为string时,执行catch块
在这里,我很难处理catch块,就像我想在值类型为字符串时执行catch块一样 在这里,当方法返回时,我使用动态类型接受所有类型的值 现在我想在方法返回字符串类型时执行catch块。 这是我的密码C#当类型为string时,执行catch块,c#,asp.net-mvc,C#,Asp.net Mvc,在这里,我很难处理catch块,就像我想在值类型为字符串时执行catch块一样 在这里,当方法返回时,我使用动态类型接受所有类型的值 现在我想在方法返回字符串类型时执行catch块。 这是我的密码 dynamic paymentResult = null; try { paymentResult = await ExecuteSquarePayment(db, checkoutViewModel); } catch (Exception ex) when (paymentResult i
dynamic paymentResult = null;
try
{
paymentResult = await ExecuteSquarePayment(db, checkoutViewModel);
}
catch (Exception ex) when (paymentResult is string)
{
return Content(HttpStatusCode.InternalServerError,
$"{Messages.DonationPaymentFailed} {checkoutViewModel.PaymentMethod} : {ex.ToString()}");
}
你不需要一个挡块<代码>重试捕获用于处理异常。如果是预期行为,只需测试
类型
:
dynamic paymentResult = null;
paymentResult = await ExecuteSquarePayment(db, checkoutViewModel);
if(paymentResult is string)
{
return Content(HttpStatusCode.InternalServerError, $"
{Messages.DonationPaymentFailed}
{checkoutViewModel.PaymentMethod} : paymentResult is a string");
}
如果出于某种原因确实需要在catch块中执行此操作,则必须抛出一个异常
:
dynamic paymentResult = null;
try
{
paymentResult = await ExecuteSquarePayment(db, checkoutViewModel);
if(paymentResult is string)
{
throw new Exception("The result was of type string");
}
}
catch (Exception ex)
{
return Content(HttpStatusCode.InternalServerError, $"
{Messages.DonationPaymentFailed}
{checkoutViewModel.PaymentMethod} : {ex.ToString()}");
}
我猜您在
ExecuteSquarePayment
中签入了正确类型的参数,对吗?如果是这样,为什么不简单地使用catch块
,而不使用类型限制呢。如果参数类型正确,则不会出现错误
对于参数可能是的其他类型,我看不到任何不同的
返回值。我猜,如果ExecuteSquarePayment方法引发异常,paymentResult将始终为null(未设置)。try catch
块用于,您应该只使用if(paymentResult为string)
。在c#6中,我们可以定义异常,我们可以使用when根据条件执行多个catch块。reference当paymentResult
仍为null
时,您希望在任何情况下引发什么异常?我想他需要ex.ToString()
来显示来自ExecuteSquarePayment
调用的一些业务异常消息,如果ExecuteSquarePayment抛出,则不会设置paymentResult,因此when条件无论如何都不会成功。您是对的,但是当返回类型为字符串时,如何测试动态类型为字符串。正如我所示if(paymentResult为string)
如果ExecuteSquarePayment
的结果为string,则将为true。ExecuteSquarePayment方法将返回动态类型这意味着该方法可能返回string、int或其他任何值