我想创建一个自定义异常过滤器,用于捕获在返回 JSON 结果的 Controller 操作中抛出的异常。
我想重构以下操作方法:
public JsonResult ShowContent()
{
try
{
// Do some business logic work that might throw a business logic exception ...
//throw new ApplicationException("this is a business exception");
var viewModel = new DialogModel
{
FirstName = "John",
LastName = "Doe"
};
// Other exceptions that might happen:
//throw new SqlException(...);
//throw new OtherException(...);
//throw new ArgumentException("this is an unhandeled exception");
return
Json(
new
{
Status = DialogResultStatusEnum.Success.ToString(),
Page = this.RenderPartialViewToString("ShowContent", viewModel)
});
}
catch (ApplicationException exception)
{
return Json(new { Status = DialogResultStatusEnum.Error.ToString(), Page = exception.Message });
}
catch (Exception exception)
{
return Json(new { Status = DialogResultStatusEnum.Exception.ToString(), Page = "<h2>PROBLEM!</h2>" });
}
}
}
我想做的是创建一个自定义异常过滤器属性,该属性将按照以下逻辑捕获操作中抛出的任何异常:
- 检查是否有异常
- 否:返回
- 是的:
- 如果 BusinessLogic 异常 – 返回 JSON 结果
- 如果有其他未处理的异常:
- 日志
- 返回另一个具有不同结果代码的 JSON 结果
最佳答案
我发现使用 this article 中的代码可以解决这个问题(略有改动。)
public class HandleJsonExceptionAttribute : ActionFilterAttribute
{
#region Instance Methods
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (filterContext.Exception != null)
{
filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
filterContext.Result = new JsonResult()
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new
{
Error = filterContext.Exception.Message
}
};
filterContext.ExceptionHandled = true;
}
}
#endregion
}
关于c# - 如何从自定义异常过滤器返回 JSON 结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5205325/