gpt4 book ai didi

c# - ID不匹配时返回错误请求

转载 作者:行者123 更新时间:2023-12-03 08:39:17 28 4
gpt4 key购买 nike

如果cardMethod.ID与付款ID不匹配,则尝试返回badrequest,但当前返回500内部服务器错误“对象引用未设置为对象的实例”我将在哪里或如何返回基于错误的信息下面的逻辑。我不确定是应该在 Controller 中处理还是应该在服务层中处理它。
目前,服务层主要处理 strip 异常。
还是应该尝试在 Controller 中实现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);
}
}
PaymentMethodController
        [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;
}
}

最佳答案

我相信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为true的情况。

关于c# - ID不匹配时返回错误请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63368323/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com