Return JSON with error status code MVC

前端 未结 11 1770
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 13:23

I was trying to return an error to the call to the controller as advised in This link so that client can take appropriate action. The controller is called by javascript via

11条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 13:45

    And if your needs aren't as complex as Sarath's you can get away with something even simpler:

    [MyError]
    public JsonResult Error(string objectToUpdate)
    {
       throw new Exception("ERROR!");
    }
    
    public class MyErrorAttribute : FilterAttribute, IExceptionFilter
    {
       public virtual void OnException(ExceptionContext filterContext)
       {
          if (filterContext == null)
          {
             throw new ArgumentNullException("filterContext");
          }
          if (filterContext.Exception != null)
          {
             filterContext.ExceptionHandled = true;
             filterContext.HttpContext.Response.Clear();
             filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
             filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
             filterContext.Result = new JsonResult() { Data = filterContext.Exception.Message };
          }
       }
    }
    

提交回复
热议问题