异常发生时如何中止提交?

问题描述

我正在使用Stripe付款,我的代码始终可用,但是如果发生异常,则无法处理HttpPost提交中的异常。

这是用户单击按钮后的入口点:

[HttpPost]
public ActionResult Checkout_Stripe()
{
    return PayWithStripe();
}

public ActionResult PayWithStripe()
{
    ... some codes here ...
    try
    {
        ... some codes here and exception happens ...
        return Json(new { id = stripeSession.Id });
    }
    catch (Exception ex)
    {
        ... execution reached here but even with below redirect,I still get HTTP 404.
        return RedirectToAction("Index","Cart");
    }
}

和我的JavaScript

<script type="text/javascript">
    var stripe = Stripe('my stripe key');
    var checkoutButton = document.getElementById('stripe-checkout-button');

    checkoutButton.addEventListener('click',function () {
        fetch('https://localhost:44323/Cart/Checkout_Stripe',{
                method: 'POST'
            })
            .then(function(response) {
                return response.json();
            })
            .then(function (session) {
                return stripe.redirecttocheckout({ sessionId: session.id });
            })
            .then(function(result) {
                if (result.error) {
                    alert(result.error.message);
                }
            })
            .catch(function(error) {
                console.error('Error:',error);
            });
    });
</script>

这是我在浏览器中看到的:

找不到资源。说明:HTTP404。资源 正在寻找(或其依赖项之一)可能已被删除, 更名,或暂时不可用。请查阅 以下网址,并确保其拼写正确。

请求的网址:/购物车

解决方法

我需要处理JavaScript以下部分中的错误

.catch(function(error) {

    // in case of error,I need to redirect to error page here
    window.location.href = "/Cart/GatewayRedirectFailed";

    console.error('Error:',error);
});