简体   繁体   English

处理MVC视图与PartialView时出错

[英]Error handling MVC Views vs PartialView

I have read a lot about error handling in MVC (specifically about applying a HandleError attribute and about using the Application_Error on the Global.asax). 我已经阅读了很多有关MVC中的错误处理的信息(特别是有关应用HandleError属性以及有关在Global.asax上使用Application_Error的信息)。 I am interested in gracefully handling the following types of exception: 我对优雅地处理以下类型的异常感兴趣:

  • Exceptions thrown inside the controller 控制器内部引发的异常
  • Exceptions thrown when performing binding of data in the view. 在视图中执行数据绑定时引发的异常。

Currently my application behaves in the following way 目前,我的应用程序的行为如下

  1. All exceptions thrown in the controller are unhandled. 控制器中引发的所有异常均未处理。 They reach the Application_Error method of the Global.asax 它们到达Global.asax的Application_Error方法
  2. All exceptions in the view are unhandled and reach the Application_Error method of the Global.asax 视图中的所有异常均未处理,并到达Global.asax的Application_Error方法
  3. Once in the Application_Error method, I log the exception, decide if the application is run locally or remotely. 一旦进入Application_Error方法,我将记录该异常,并确定该应用程序是在本地运行还是在远程运行。 If so, I present the yellow screen to the user, or perform a Response.Redirect to custom error pages. 如果是这样,我向用户显示黄色屏幕,或执行Response.Redirect到自定义错误页面。

This logic works correctly for errors thrown inside controllers that render parent views or the parent view itself. 对于在渲染父视图或父视图本身的控制器中引发的错误,此逻辑正确起作用。 The downside of this logic is that, when an error is thrown inside a Child Action which should render a PartialView the whole page becomes unusable. 这种逻辑的缺点是,当在子动作中引发错误时,该动作应呈现PartialView,整个页面将变得无法使用。 This because the yellow error screen or the custom error page occupies the complete page and wont allow the user to view the other sections of the webpage. 这是因为黄色错误屏幕或自定义错误页面占据了整个页面,并且不允许用户查看网页的其他部分。

What I want to do/know is if it is possible to: 我想/知道的是是否可以:

  1. Display the yellow error screen inside of a partial view but render the rest of the page correctly. 在部分视图内显示黄色错误屏幕,但正确呈现页面的其余部分。
  2. Redirecting the user to a partial view error page that allows for the rest of the page to remain usable. 将用户重定向到部分视图错误页面,该页面允许其余页面保持可用。

To handle this specific case: 要处理此特定情况:

"when an error is thrown inside a Child Action which should render a PartialView the whole page becomes unusable." “当在子动作中引发错误时,该动作应导致PartialView整个页面变得不可用。”

You can define a global Ajax event handler for "ajaxError" to handle exception thrown from an action that is called using "@Html.Partial". 您可以为“ ajaxError”定义一个全局Ajax事件处理程序,以处理使用“ @ Html.Partial”调用的操作引发的异常。

Apart from handling all errors in "Application_Error" we have defined following global handler in _Layout.cshtml. 除了处理“ Application_Error”中的所有错误外,我们还在_Layout.cshtml中定义了以下全局处理程序。 This basically handle cases where a partial view was invoked from html and the action threw an exception. 这基本上可以处理从html调用部分视图而该操作引发异常的情况。 If an error is encountered, data is logged and toastr popup message is displayed. 如果遇到错误,将记录数据并显示烤面包机弹出消息。

_Layout.cshtml: _Layout.cshtml:

    //Ajax Global Event Loader
    globalVar: ajaxContainer = $('div[id=wrap]');
    $(document).bind("ajaxSend", function () {
        if ($('.k-loading-mask').is("visible") == false) {
            var loader = new ajaxLoader(ajaxContainer, { bgColor: '#fff', duration: 800, opacity: 0.3, classOveride: false });
        }
    }).bind("ajaxComplete", function () {
        if ($('div[class=ajax_overlay]').is(':visible') == true)
            $('div[class=ajax_overlay]').remove();
    }).bind("ajaxError", function (event, jqxhr, settings, thrownError) {
        //debugger;
        $('div[class=ajax_overlay]').remove();
        $('.k-loading-image').remove();
        if ((settings.url.indexOf('Notification/GetActiveNotificationByUserName') < 0)
            && (settings.url.indexOf('LogError/LogData') < 0)) {
            var errorData = 'URL: ' + settings.url + '; Type: ' + settings.type + '; Data: ' + settings.data + '; thrownError: ' + thrownError;
            var model = { errorData: errorData };

            $.ajax({
                url: '@Url.Action("LogData", "LogError")',
                contentType: 'application/json; charset=utf-8',
                type: 'POST',
                dataType: 'html',
                data: JSON.stringify(model)
            })
            .success(function (result) {
                $("div.overlay").hide();
            })
            .error(function (xhr, status) {
                $("div.overlay").hide();
                //alert(status);
            });

            // Set toastr for error notification and display error 1 at a time
            toastr.options.closeButton = true;
            toastr.options.positionClass = 'toast-top-full-width';
            toastr.options.showMethod = 'slideDown';
            toastr.options.hideMethod = 'slideUp';
            toastr.options.showDuration = '1000';
            toastr.options.hideDuration = '1';
            toastr.clear();
            toastr.error('Your request cannot be processed right now. Please try again later!');
        }

        $("div.overlay").hide();
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM