gpt4 book ai didi

asp.net-mvc-3 - MVC 3 json 请求应在异常时收到 json 响应

转载 作者:行者123 更新时间:2023-12-01 22:53:53 25 4
gpt4 key购买 nike

我正在寻找一种良好/智能/干净的方法来全局处理错误,以便如果请求是 Json 并且发生异常,结果应该是 json 而不是 html。

寻找现有的解决方案或一些如何构建我自己的解决方案的信息。

最佳答案

一种常见的方法是编写自定义异常过滤器:

public class MyErrorHandlerAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
filterContext.ExceptionHandled = true;
filterContext.Result = new JsonResult
{
Data = new { success = false, error = filterContext.Exception.ToString() },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}

可以在 Global.asax 中注册为全局过滤器。然后简单地查询一些操作:

$.getJSON('/someController/someAction', function (result) {
if (!result.success) {
alert(result.error);
} else {
// handle the success
}
});

关于asp.net-mvc-3 - MVC 3 json 请求应在异常时收到 json 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5859765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com