[Original] ASP. net mvc Exception Handling Solution

Source: Internet
Author: User

Exception Handling is a required function of every system. Especially for Web Systems, a simple and unified exception handling mode is particularly important. When you plan to use ASP. when net MVC is used as a project, this problem occurs on the first data entry page.

In the previous ASP. in the net webform project, it is generally carried out in the application_error event processor and scriptmanager_asyncpostbackerror event processor, in ASP. net MVC does not seem to be suitable for using either of the two methods. Where should I place it? You will not always put a try {...} catch {...} in each action.

In scottgu's blog, I mentioned a class: handleerrorattribute, which seems to be used to handle exceptions. So I used handleerrorattribute to try it. (note,If this type is used and you want to display exceptions in the specified view, you must. <system. web> Add <customerrors mode = "on"/>) Handleerror is indeed easy to use. You can use its view attribute to specify the page to jump to after an exception. You can jump to different view for different exception types to display the exception, you can also display the view to the current view without redirecting to an exception. For example:

 
[Httppost] [handleerror (view = "CREATE", exceptiontype = typeof (exception)] public actionresult create (string someparam) {Throw new exception ("Oops... ");}

When an exception occurs, the page will jump back to create, but there is a small problem, the user entered a lot on the page, if you tell me that an exception will not cause him to lose anything that has been hard for a long time. If you send such a project out, it will be changed sooner or later.

open the Source Code of handleerrorattribute to view the following key parts:

Public Virtual void onexception (exceptioncontext filtercontext) {If (filtercontext = NULL) {Throw new argumentnullexception ("filtercontext");} If (filtercontext. ischildaction) {return;} // If custom errors are disabled, we need to let the normal ASP. net exception handler // execute so that the user can see useful debugging information. if (filtercontext. exceptionhandled |! Filtercontext. httpcontext. iscustomerrorenabled) {return;} exception = filtercontext. exception; // if this is not a HTTP 500 (for example, if somebody throws an HTTP 404 from an action method), // ignore it. if (New httpexception (null, exception ). gethttpcode ()! = 500) {return;} If (! Predictiontype. isinstanceoftype (exception) {return;} string controllername = (string) filtercontext. routedata. values ["controller"]; string actionname = (string) filtercontext. routedata. values ["action"]; handleerrorinfo model = new handleerrorinfo (filtercontext. exception, controllername, actionname); filtercontext. result = new viewresult {viewname = view, mastername = Master, viewdata = new viewdatadictionary 

As you can clearly see, MVC actually creates a viewresult using the view name we just specified, and then submits the viewresult to the invokeactionresult method, which is finally displayed to the user. In this process, the viewdata of the new viewresult is set to handleerrorinfo, and the data on create is not put into viewdata, although the previous Params content is still saved in the request of the "Create View" shown later, but the data is not loaded, I did not go into it. I feel that if I directly put filtercontext here. viewdata In the controller is directly used as the viewdata of the new viewresult, it is certainly able to display the data before submission (because if the exceptionCodeThe package in try... catch... can display the previous data after an exception ).

So I created a new exceptionfitler:

Public class customhandleerrorattribute: filterattribute, iexceptionfilter {public void onexception (exceptioncontext filtercontext) {filtercontext. controller. viewdata ["exception"] = filtercontext. exception; filtercontext. result = new viewresult () {viewname = filtercontext. controller. controllercontext. routedata. values ["action"]. tostring (), viewdata = filtercontext. controller. viewdata}; filtercontext. exceptionhandled = true; filtercontext. httpcontext. response. tryskipiiscustomerrors = true ;}}

The class name should be used later :)

Modify the original action as follows:

 
[Httppost] [customhandleerror] public actionresult create (string name) {Throw new exception ("Oops ...");}

Add the following code to create. csthml:

If (viewdata ["exception"]! = NULL) {var EX = viewdata ["exception"] as exception; @ ex. Message}

F5, after the submission, it returned to the original view, and the data filled in earlier was still there.

The improvements in March 19 are as follows :-----------------------------------------

Namespace system. web. MVC {public class handleexceptionattribute: handleerrorattribute, iexceptionfilter {# region iexceptionfilter members public override void onexception (exceptioncontext filtercontext) {If (filtercontext = NULL) {Throw new argumentnullexception ("filtercontext");} If (filtercontext. ischildaction) {return;} // If custom errors are disabled, we need to let the normal ASP. net Exception handler // execute so that the user can see useful debugging information. If (filtercontext. exceptionhandled |! Filtercontext. httpcontext. iscustomerrorenabled) {return;} exception = filtercontext. exception; // if this is not a HTTP 500 (for example, if somebody throws an HTTP 404 from an action method), // ignore it. if (New httpexception (null, exception ). gethttpcode ()! = 500) {return;} If (! Predictiontype. isinstanceoftype (exception) {return;} string actionname = (string) filtercontext. routedata. values ["action"]; filtercontext. controller. viewdata ["exception"] = exception; filtercontext. result = new viewresult () {viewname = actionname, viewdata = filtercontext. controller. viewdata}; filtercontext. exceptionhandled = true; filtercontext. httpcontext. response. clear (); filtercontext. httpcontext. response. statuscode = 500; filtercontext. httpcontext. response. tryskipiiscustomerrors = true;} # endregion} public static class handleexceptionhelper {public static exception (this htmlhelper) {var exception = htmlhelper. viewcontext. controller. viewdata ["exception"] as exception; return exception ;}}}

View is used as follows:

 
If (@ html. Exception ()! = NULL) {@ html. Exception (). Message}

Add and generate the jquery error style in April March 20 :------------------------------------------------

Public static class handleexceptionhelper {public static exception (this htmlhelper) {var exception = htmlhelper. viewcontext. controller. viewdata ["exception"] as exception; return exception;} public static mvchtmlstring jquerystyleerror (this htmlhelper) {var exception = Exception (htmlhelper); If (exception = NULL) {return NULL;} tagbuilder builder = new tagbuild Er ("Div"); builder. generateid ("editordescription"); builder. addcssclass ("UI-widget UI-state-error UI-corner-all"); builder. innerhtml = string. format (@ "<p> <SPAN class =" "UI-Icon UI-icon-alert" "style =" "float: Left; margin-Right :. 3em; ""> </span> <strong> {0 }:</strong> {1} </P> ", resx. error, String. isnullorempty (exception. message )? Resx. unknowerrormessage: exception. Message); return New mvchtmlstring (builder. tostring (tagrendermode. Normal ));}}

The view application is as follows:

 
@ Html. jquerystyleerror ()

The effect is as follows:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.