我使用jquery ajax调用了很多方法。
为了处理fail方法中的任何错误,我使用以下代码;
public async Task<ActionResult> UpdateStockTransactionAsync(
string TransactionDate, string Quantity, string ProductId, string TabCount)
{
try
{
//my code goes here
}
catch (System.Web.Http.HttpResponseException ex)
{
var msg = ex.Response.Content.ReadAsStringAsync().Result;
var errorModel = JsonConvert.DeserializeObject<AcknowledgementModel>(msg);
return new HttpStatusCodeResult(500, errorModel.errormessage);
}
catch (Exception ex)
{
return new HttpStatusCodeResult(500, ex.Message);
}
}
我似乎在我的代码中重复了这么多,是否有可能将其拉出到过滤器属性?如果是这样的话?
答案 0 :(得分:2)
一种选择是使用Controller类上可用的可覆盖方法OnException。
protected override void OnException(ExceptionContext filterContext)
{
var exception = filterContext.Exception;
if (exception is System.Web.Http.HttpResponseException) // Catch HttpResponseException
{
var msg = ex.Response.Content.ReadAsStringAsync().Result;
var errorModel = JsonConvert.DeserializeObject<AcknowledgementModel>(msg);
filterContext.Result = new HttpStatusCodeResult(500, errorModel.errormessage);
}
else // catch (Exception ex)
{
filterContext.Result = new HttpStatusCodeResult(500, ex.Message);
}
base.OnException(filterContext);
}
您可以使用filterContext.Result