4

例外をキャプチャし、ユーザーをエラーページにリダイレクトしています。例外メッセージと戻りURLを渡して、何が起こったかをユーザーに通知し、ユーザーが別のページを返すことができるようにします。

        try
        {
            return action(parameters);
        }
        catch (Exception exception)
        {
            ErrorViewModel errorModel = new ErrorViewModel();
            errorModel.ErrorMessage = "An error occured while doing something.";
            errorModel.ErrorDetails = exception.Message;
            errorModel.ReturnUrl = Url.Action("Controller", "Action");
            return RedirectToAction("Index", "Error", errorModel);
        }

これは、すべてのアクションをラップするにはコードが多すぎるようです。エラーにグローバルフィルターを使用しています:

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        HandleErrorAttribute attribute = new HandleErrorAttribute();
        filters.Add(attribute);
    }

そして、私は次のようにweb.configを設定しています。

<customErrors mode="On" defaultRedirect="~/Error/Unknown">

ただし、これは未処理の例外に対してのみ機能します。

例外によって、例外の詳細を保持するパラメーターを取得するエラーコントローラー/アクションにリダイレクトされるようにしたい。アクションごとにリターンURLを指定できるか、何も提供されていない場合はデフォルトを設定できると便利です。

4

2 に答える 2

4

これが私が作成した小さなRedirectOnErrorAttributeクラスです:

using System;
using System.Web.Mvc;
using MyApp.Web.Models;

namespace MyApp.Web.Utilities
{
    public class RedirectOnErrorAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// Initializes a new instance of a RedirectOnErrorAttribute.
        /// </summary>
        public RedirectOnErrorAttribute()
        {
            ErrorMessage = "An error occurred while processing your request.";
        }

        /// <summary>
        /// Gets or sets the controller to redirect to.
        /// </summary>
        public string ReturnController { get; set; }

        /// <summary>
        /// Gets or sets the action to redirect to.
        /// </summary>
        public string ReturnAction { get; set; }

        /// <summary>
        /// Gets or sets the error message.
        /// </summary>
        public string ErrorMessage { get; set; }

        /// <summary>
        /// Redirects the user to an error screen if an exception is thrown.
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (filterContext.Exception != null && !filterContext.ExceptionHandled)
            {
                ErrorViewModel viewModel = new ErrorViewModel();
                viewModel.ErrorMessage = ErrorMessage;
                viewModel.ErrorDetails = filterContext.Exception.Message;
                string controller = ReturnController;
                string action = ReturnAction;
                if (String.IsNullOrWhiteSpace(controller))
                {
                    controller = (string)filterContext.RequestContext.RouteData.Values["controller"];
                }
                if (String.IsNullOrWhiteSpace(action))
                {
                    action = "Index";
                }
                UrlHelper helper = new UrlHelper(filterContext.RequestContext);
                viewModel.ReturnUrl = helper.Action(action, controller);
                string url = helper.Action("Index", "Error", viewModel);
                filterContext.Result = new RedirectResult(url);
                filterContext.ExceptionHandled = true;
            }
            base.OnActionExecuted(filterContext);
        }
    }
}

これで、すべてのアクションを次のように装飾できます。

[RedirectOnError(ErrorMessage="An error occurred while doing something.", ReturnController="Controller", ReturnAction="Action")]
于 2012-01-12T13:07:36.087 に答える
4

すべてのアクションに try catch を配置する代わりに、コントローラーの OnException イベントをオーバーライドできます。そのイベントには、すべての例外の詳細が含まれています。他のすべての設定は正しく見えます。

    [HandleError]
    public class AccountController : Controller
    {
       [HttpPost]
       public ActionResult YourAction(SomeModel model)
        {
            //do stuff but don't catch exception
            return View();
        }
        protected override void OnException(ExceptionContext filterContext)
        {
            EventLog.WriteEntry("YourProjectEventName", filterContext.Exception.ToString(), EventLogEntryType.Error);
            base.OnException(filterContext);
       }
}
于 2012-01-11T19:22:37.023 に答える