【问题标题】:Return a bad request when ID doesn't matchID 不匹配时返回错误请求
【发布时间】:2020-12-01 17:14:15
【问题描述】:

如果 cardMethod.ID 与付款 ID 不匹配,则尝试返回 badrequest,但目前它返回 500 内部服务器错误“对象引用未设置为对象的实例”我将在哪里或如何返回基于以下逻辑的错误。我不确定是应该在控制器中处理还是应该在服务层中处理。

目前服务层主要处理条带异常。

或者我应该尝试在我的控制器中实现一个 try catch 吗?

服务等级

        public async Task<VersionResponse> DeletePaymentMethod(string paymentID, string userId)
        {
            try
            {
                StripeConfiguration.ApiKey = _appSettings.StripeSecretKey;

                var profile = await _userManager.FindByIdAsync(userId);

                var stripeId = profile.StripeAccountId;

                if (stripeId == null)
                    throw new ArgumentException("No associated Stripe account found.");

                var service = new PaymentMethodService();

                //list the payment methods
                var cardPaymentMethods = service.ListAutoPaging(new PaymentMethodListOptions
                {
                    Customer = stripeId,
                    Type = "card"
                });

                //Detach card which matches with list of payment methods
                var cardMethod = cardPaymentMethods.Where(m => m.Id == paymentID).FirstOrDefault(); 

                if(cardMethod.Id != paymentID)
                    throw new ArgumentException("Payment method not found for specified id.");

                await service.DetachAsync(cardMethod.Id, new PaymentMethodDetachOptions());

                return new VersionResponse
                {
                    Data = cardPaymentMethods
                };
            }
            catch (Exception ex)
            {
                throw HandleStripeExceptions(ex);
            }
        }

支付方法控制器

        [HttpDelete]
        [ProducesResponseType(typeof(FluentValidation.Results.ValidationResult), 400)]
        public async Task<IActionResult> DeletePaymentMethod(string paymentID)
        {
            var userId = User.Claims.FirstOrDefault(x => x.Type == "UserID").Value;
            var result = new SuccessResponse()
            {
                success = true
            };

            
            await _paymentService.DeletePaymentMethod(paymentID, userId);

            if (string.IsNullOrEmpty(paymentID))
                return BadRequest("Payment method not found for specified id.");

            return Ok(result);
        }

    private Exception HandleStripeExceptions(Exception ex)
    {
        if (ex is StripeException e)
        {
            switch (e.StripeError.ErrorType)
            {
                case "card_error":
                    Console.WriteLine("Code: " + e.StripeError.Code);
                    Console.WriteLine("Message: " + e.StripeError.Message);
                    break;
                case "api_connection_error":
                    break;
                case "api_error":
                    break;
                case "missing_parameter":
                    break;
                case "authentication_error":
                    break;
                case "rate_limit_error":
                    break;
                case "validation_error":
                    break;

                default:
                    // Unknown Error Type
                    break;
            }

            return ex;
        }
        else
        {
            return ex;
        }
    }

【问题讨论】:

  • 你调试代码了吗?代码中的哪一行抛出异常?
  • 将await _paymentService.DeletePaymentMethod(paymentID, userId);移动到if()检查下方
  • @zaitsman 我试过了,但它仍然没有成功 - 它在这里抛出 500 错误 if(cardMethod.Id != paymentID) 但没有捕捉到我的异常
  • _paymentService.DeletePaymentMethod throws HandleStripeExceptions 但它没有在控制器代码中处理...
  • @ChetanRanpariya 所以我必须调用 HandleStripeExceptions 吗?在我的控制器中?

标签: c# rest error-handling stripe-payments


【解决方案1】:

我相信500 错误是由于

if(cardMethod.Id != paymentID)
  throw new ArgumentException("Payment method not found for specified id.");

cardMethod可以是null,你应该在if语句中检查null

if(cardMethod == null)

不会有cardMethod.Id != paymentID 为真的情况。

【讨论】:

  • 我已经尝试过,由于某种原因,它捕获了该行上的错误 - 抛出 System.NullReferenceException: 'Object reference not set to an instance of an object。 5__6 为空。
  • 但是当我单步执行时,它会返回控制器并检查 deletepayments 是否成功,如果不成功,它会转到我的通用异常处理程序,该处理程序只会返回 500 错误消息
  • 对不起,我的回答稍作修改,你应该检查if(cardMethod == null)。
  • 那不是一样的输出吗?
猜你喜欢
  • 2020-08-11
  • 2018-07-18
  • 1970-01-01
  • 2019-11-12
  • 1970-01-01
  • 2019-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多