2011-03-05 629 views
6

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

我希望做的是创建一个自定义异常过滤器属性,将捕获的行动引发的任何异常遵循以下逻辑:

  1. 检查是否有异常
    • 号:返回
    • 是:
      • 如果BusinessLogic异常 - 返回一个JSON结果
      • 如果其它未处理的异常:
        • 登录
        • 返回另一个JSON结果有不同的结果代码

回答

-2
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 attribute

* 编辑为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 
      } 
     } 
+0

谢谢swapneel,但我想创建一个过滤属性th在我将用来装饰我的控制器操作返回JSON - 我不想重写OnException方法。 – Elie 2011-03-05 19:40:14

+0

你有要求 - 自定义异常过滤器属性在你的问题? – swapneel 2011-03-05 20:21:07

+0

看到我的*编辑HandleAttribute的行动* – swapneel 2011-03-06 00:30:11

15

我发现有可能解决使用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 
} 
+2

这应该是正确的答案 – CMS 2016-02-16 21:01:17

+1

我同意这应该是正确的答案。但是,1.1中有一个错误(?),它不需要将ExceptionHandled设置为true。如果你做的响应的主体将是空的。 – JD987 2017-02-15 23:20:44