如何从自定义异常过滤器返回 JSON 结果?

发布于 2024-10-20 14:36:00 字数 1692 浏览 3 评论 0原文

我想创建一个自定义异常过滤器,它将捕获返回 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>" });
        }
    }
}

我想做的是创建一个自定义异常过滤器属性,该属性将捕获操作中引发的任何异常,遵循以下逻辑:

  1. 检查是否有异常
    • 否:返回
    • 是的:
      • 如果 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:

  1. 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

手心的海 2024-10-27 14:36:00

我发现可以使用 本文 中找到的代码解决此问题(使用对其进行微小的修改。)

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
}

I found it possible to solve this problem using the code found in this article (with minor changes to it.)

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
}
如日中天 2024-10-27 14:36:00
  public class YourController : BaseController
    {
        public JsonResult showcontent()
        {
            // your logic here to return foo json
            return Json ( new { "dfd" }); // just a dummy return text replace it wil your code
        }
    }

    public class BaseController : Controller
    {
 // Catch block for all exceptions in your controller
        protected override void OnException(ExceptionContext filterContext)
        {
            base.OnException(filterContext);
            if (filterContext.Exception.Equals(typeof(ApplicationException)))
            {
                //do  json and return
            }
            else
            {
                // non applictaion exception
// redirect to generic error controllor and error action which will return json result

            }
        }

    }

请参阅此链接以了解如何创建和使用 HandleError 属性

*编辑操作的 HandleAttribute*

//not tested code
public class HandleErrorfilter : HandleErrorAttribute
    {
         public string ErrorMessage { get; set; }

        public override void OnException(ExceptionContext filterContext)
        {
                string message = string.Empty;
                //if application exception
                // do  something
                 else
                    message = "An error occured while attemting to perform the last action.  Sorry for the inconvenience.";
            }
            else
            {
                base.OnException(filterContext);
            }
        }

      public class YourController : BaseController
        {
            [HandleErrorfilter]
            public JsonResult showcontent()
            {
                // your logic here to return foo json
                return Json ( new { "dfd" }); // just a dummy return text replace it wil your code
            }
        }
  public class YourController : BaseController
    {
        public JsonResult showcontent()
        {
            // your logic here to return foo json
            return Json ( new { "dfd" }); // just a dummy return text replace it wil your code
        }
    }

    public class BaseController : Controller
    {
 // Catch block for all exceptions in your controller
        protected override void OnException(ExceptionContext filterContext)
        {
            base.OnException(filterContext);
            if (filterContext.Exception.Equals(typeof(ApplicationException)))
            {
                //do  json and return
            }
            else
            {
                // non applictaion exception
// redirect to generic error controllor and error action which will return json result

            }
        }

    }

Refer this link to see how to create and use HandleError attribute

*EDIT for HandleAttribute for Actions*

//not tested code
public class HandleErrorfilter : HandleErrorAttribute
    {
         public string ErrorMessage { get; set; }

        public override void OnException(ExceptionContext filterContext)
        {
                string message = string.Empty;
                //if application exception
                // do  something
                 else
                    message = "An error occured while attemting to perform the last action.  Sorry for the inconvenience.";
            }
            else
            {
                base.OnException(filterContext);
            }
        }

      public class YourController : BaseController
        {
            [HandleErrorfilter]
            public JsonResult showcontent()
            {
                // your logic here to return foo json
                return Json ( new { "dfd" }); // just a dummy return text replace it wil your code
            }
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文