如何从自定义异常过滤器返回 JSON 结果?
我想创建一个自定义异常过滤器,它将捕获返回 JSON 结果的控制器操作中引发的异常。
我想重构以下操作方法:
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 结果
I would like to create a custom exception filter that will catch exceptions thrown in controller actions that return JSON results.
I would like to refactor the following action method:
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>" });
}
}
}
What I would like to do is create a custom exception filter attribute that will catch any exceptions thrown in the action follow the following logic:
- Check if there was an exception
- No: return
- yes:
- If BusinessLogic exception – return a JSON result
- If other unhandled exception:
- Log
- Return another JSON result with a different result code
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我发现可以使用 本文 中找到的代码解决此问题(使用对其进行微小的修改。)
I found it possible to solve this problem using the code found in this article (with minor changes to it.)
请参阅此链接以了解如何创建和使用 HandleError 属性
*编辑操作的 HandleAttribute*
Refer this link to see how to create and use HandleError attribute
*EDIT for HandleAttribute for Actions*