答えて

0

OnExceptionイベントで独自のベースコントローラを作成し、例外を処理することができます。

public class BaseController : Controller 
{ 
    protected override void OnException(ExceptionContext filterContext) 
    { 
     // to do : Log the exception (filterContext.Exception) 
     // and redirect/return error view 
     filterContext.ExceptionHandled = true; 
     // If the exception occurred in an ajax call. Send a json response back 
     // (you need to parse this and display to user as needed at client side) 
     if (filterContext.HttpContext.Request.Headers["X-Requested-With"] 
                  =="XMLHttpRequest") 
     { 
      filterContext.Result = new JsonResult 
      { 
       JsonRequestBehavior = JsonRequestBehavior.AllowGet, 
       Data = new { Error = true, Message = filterContext.Exception.Message } 
      }; 
      filterContext.HttpContext.Response.StatusCode = 500; // Set as needed 
     } 
     else 
     { 
      filterContext.Result = new ViewResult { ViewName = "Error.cshtml" }; 
      //Assuming the view exists in the "~/Views/Shared" folder 
     } 
    } 
} 

アヤックス以外のリクエストの場合は、Error.cshtmlをユーザーに表示します。 Error.cshtmlを表示する代わりにErrorアクションメソッドにリダイレクト(新しいGET呼び出し)を行う場合は、ViewResultRedirectToRouteResultに置き換えることができます。

filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { 
               {"controller", "Home"}, {"action", "Error"} 
               }; 

は今、あなたの他のコントローラは、あなたが望むものは明らかではない。この

public class HomeController : BaseController 
{ 
    public ActionResult Die() 
    { 
     throw new Exception("Bad code!"); 
    } 
} 
public class ProductsController : BaseController 
{ 
    public ActionResult Index() 
    { 
     var arr =new int[2]; 
     var thisShouldCrash = arr[10]; 
     return View(); 
    } 
} 
+0

ありがとうございました。私はこれを試してみる。 @shyju – bethisdname

関連する問題