Sivamohan Reddy
Sivamohan Reddy

Reputation: 574

C# Execute the catch block when the type is string

Here I'm struggling to work with catch block like I wanted to execute the catch block when the value type is a string.

Here I'm using dynamic type to accept all the type of values when the method will returns.

Now I wanted to execute the catch block when the method will return the string type. Here my code is

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

Upvotes: 0

Views: 117

Answers (3)

I guess, if the ExecuteSquarePayment method throws an exception, paymentResult will always be null(not set).

Upvotes: 0

Romano Zumbé
Romano Zumbé

Reputation: 8089

You don't need a catch block for this. try-catch is used to handle exceptions. If it is an expected behavior just test for the type:

 dynamic paymentResult = null;

 paymentResult = await ExecuteSquarePayment(db, checkoutViewModel);

 if(paymentResult is string)
 {
      return Content(HttpStatusCode.InternalServerError, $"
           {Messages.DonationPaymentFailed} 
           {checkoutViewModel.PaymentMethod} : paymentResult is a string");
 }

If for some reason you really need to do it in a catch block you will have to throw an Exception:

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

Upvotes: 1

Mihail Stancescu
Mihail Stancescu

Reputation: 4138

I'm guessing that you check in ExecuteSquarePayment for the correct type of the argument, right? If so, why not simply use the catch block with out the type restriction. If the argument type is correct there won't be an error.

I don't see any different return for other types that the argument may be.

Upvotes: 0

Related Questions