2011-03-05 13 views
6

Me gustaría crear un filtro de excepción personalizado que capture las excepciones lanzadas en las acciones del controlador que devuelven los resultados de JSON.Cómo devolver el resultado JSON de un filtro de excepción personalizado?

me gustaría refactorizar el método siguiente acción:

 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>" }); 
     } 
    } 
} 

Lo que me gustaría hacer es crear un atributo de filtro de excepción personalizada que captura cualquier excepción lanzada en la acción sigue la siguiente lógica:

  1. comprobar si había una excepción
    • No: volver
    • sí:
      • Si BusinessLogic excepción - devuelve un resultado JSON
      • Si otra excepción no controlada:
        • Entrar
        • Retorno otro resultado JSON con un código de resultado diferente

Respuesta

-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 

      } 
     } 

    } 

Consulte este enlace para ver la forma de crear y utilizar HandleError attribute

* EDITAR para HandleAttribute de acciones *

//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

Gracias swapneel pero me gustaría crear un atributo de filtro th en Voy a utilizar para decorar mis acciones de controlador que devuelven JSON - No estoy buscando sobreescribir el método OnException. – Elie

+0

que ha solicitado para - atributo de filtro de excepción personalizado en su pregunta? – swapneel

+0

ver mi * EDITAR para HandleAttribute para acciones * – swapneel

15

encontré posible resolver este problema utilizando el código que se encuentra en this article (con pequeños cambios en él.)

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

esta debería ser la respuesta correcta – CMS

+1

Acepto que esta debería ser la respuesta correcta. Sin embargo, hay un error (?) En 1.1 que requiere no establecer ExceptionHandled en verdadero. Si lo haces, el cuerpo de la respuesta estará vacío. – JD987

Cuestiones relacionadas