【发布时间】: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.DeletePaymentMethodthrowsHandleStripeExceptions但它没有在控制器代码中处理... -
@ChetanRanpariya 所以我必须调用 HandleStripeExceptions 吗?在我的控制器中?
标签: c# rest error-handling stripe-payments