如何解决ID不匹配时返回错误请求
如果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);
}
}
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
都是正确的。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。