ASP. NET AJAX Starter Series (8): Custom Exception Handling

Source: Internet
Author: User

ASP. NET AJAX Starter Series (8): Custom Exception Handling

In the event of an asynchronous update to the UpdatePanel control, if an error occurs, an alert dialog box appears by default to display the error message, which is unfriendly to the user, and this article looks at how to customize exception handling in server and client script, translated from official documents.

Main content

1. Custom exception handling on the server side

2. Customizing exception Handling in client script

A Custom exception handling on the server side

1. Add an ASPX page and switch to Design view.

2. In the Toolbox, under the AJAX Extensions tab, double-click ScriptManager and UpdatePanel controls to add to the page.

3. In the UpdatePanel control, add two textbox, a label, a button and some text, and set the button's Text property value to "Calculate".

4. Double-click the Calculate button and add the following code to the event handler.


TextBox1.Text + "by" + TextBox2.Text + ".";

}
Throw ex;
}
}

A Try-catch statement block is included in the event-handling code, the division is performed in the try, and if the operation fails, the ExtraInfo information is set in the catch and the exception is re-thrown.

5. Switch to Design view and select the ScriptManager control.

6. In the Properties window, in the toolbar, select the Events button, and double-click Asyncpostbackerror.

7. Add the following code to the Asyncpostbackerror event handler.

}
}

Detects if the extrainfo of the exception is empty and is set to the asyncpostbackerrormessage of the ScriptManager control, and a default exception is created if not set.

8. Save and press CTRL + F5 to run.

9. Enter a number greater than 0 in each text box, and click the Calculate button to submit the success.

10. Enter 0 in the second text box, and clicking Calculate will throw an exception. The browser will display a dialog box that prompts you for information that we set on the server.

Two Customizing exception Handling in client script

The preceding exception handling is handled by setting the properties of the ScriptManager control on the service side, and the following is a look at how to use the PageRequestManager class in client script for exception handling and <div> element instead of the default Alert dialog box for the browser.

1. In the page that we created earlier, switch to Code view.

2. Add the following HTML elements to the page (some errors in the official documentation)


<div id= "Alertmessage" >

</div>

<br/>

<div id= "Alertbuttons" >

<input id= "OKButton" type= "button" value= "OK" runat= "server" onclick= "clearerrorstate ()"/>

</div>

</div>

3. Add the following style tag to the head element.


#UpdatePanel1 {

width:200px; height:50px;

Border:solid 1px Gray;

}

#AlertDiv {

left:40%; top:40%;

Position:absolute; width:200px;

padding:12px;

border: #000000 1px solid;

Background-color:white;

Text-align:left;

Visibility:hidden;

z-index:99;

}

#AlertButtons {

Position:absolute; right:5%; bottom:5%;

}

</style>

4. Switch to Design view and make sure your page looks like the following.

5. In the Properties window, select the document element (which corresponds to page <Body> element) in the drop-down list and set the ID property value to Bodytag.

6. Switch to Code view.

7. Add the following <script> code block.


var Divelem = ' AlertDiv ';

var Messageelem = ' alertmessage ';

var bodytag = ' Bodytag ';

Sys.WebForms.PageRequestManager.getInstance (). Add_endrequest (Endrequesthandler);

function Togglealertdiv (visstring)

{

if (visstring = = ' hidden ')

{

$get (bodytag). Style.backgroundcolor = ' white ';

}

Else

{

$get (bodytag). Style.backgroundcolor = ' Gray ';



}

var adiv = $get (Divelem);

adiv.style.visibility = visstring;



}

function Clearerrorstate () {

$get (messageelem). InnerHTML = ";

Togglealertdiv (' hidden ');

}

function Endrequesthandler (sender, args)

{

if (Args.get_error ()! = undefined)

{

var errormessage;

if (Args.get_response (). get_StatusCode () = = ' 200 ')

{

ErrorMessage = Args.get_error (). Message;

}

Else

{

Error occurred somewhere other than the server page.

ErrorMessage = ' An unspecified error occurred. ‘;

}

Args.set_errorhandled (TRUE);

Togglealertdiv (' visible ');

$get (messageelem). InnerHTML = errormessage;

}

}

</script>

In the code block, the following are the main things to do:

1) defines the EndRequest event handling for the PageRequestManager class, which, in event handling, displays AlertDiv when an error occurs.

2) define the TOGGLEALERTDIV function, which is used to display or hide the AlertDiv element when an error occurs, and to change the background color of the page.

3) Define the Clearerrorstate function, which is used to hide the error message UI.

8. Save and press CTRL + F5 to run.

9. Enter a number greater than 0 in each text box, and click the Calculate button to submit the success.

10. Enter 0 in the second text box, and clicking Calculate will throw an exception. The custom alertdiv will be displayed instead of the Default Alert dialog box, as shown in:

[translated from official documents]

Support Terrylee's entrepreneurial product Worktile
Worktile, a new generation of easy to use, experience the ultimate team collaboration, project management tools, let you and your team work together anytime, anywhere. It's completely free, so get to know it now.
https://worktile.com Category: [[] web Development, [] Ajax Storm Green channel: Good text to the top of my collection This article contact me Terrylee
Follow-33
Followers-2798 + Plus follow 1 0 (please comment on the article) «Previous: Follow Web Client software Factory [Weekly Drop 08]
» Next: ASP (9): Use updatepanelposted in master pages @ 2006-11-13 16:58 Terrylee Read (18096) Comments (37) Edit Favorites

Comment List reply reference # F building 2006-11-14 10:39 charming[Anonymous [unregistered users]:) Reply Quote # 0 Lou 2006-11-15 17:01 Kevin Wu Good, again out of the new, continue to work hard, continue to pay attention to, thanks to share:) support () against (0) reply to quote [landlord] 2006-11-15 20:04 Terrylee @Kevin Wu
:) Support (0) against (0) reply to quote # A building 2006-11-16 16:29 Ajax Primer [unregistered user] boss is not three little pieces of code, ah, can't run.
<div id= "AlertDiv" language= "JavaScript" onclick= "return Alertdiv_onclick ()" > where is this function? Reply Reference # # Building 2006-11-17 15:21 guest[unregistered user] No, it's not good to reply to the 2006-11-17 22:00 Asharp. or pop-up server exception handling support (0) objection (0) Reply Quote # # Building [landlord] 2006-11-18 18:00 Terrylee @ Chen fluttering
Translated from official documents
Please refer to:
Http://ajax.asp.net Support (0) against (0) reply to the reference to the building 2006-11-20 15:18 Kevin Lin This example is wrong, Terrylee people? :) Support (0) objection (0) Reply Quote # building 2006-11-21 16:23 Heaven has a way you don't go [unregistered users] just get rid of that onclick event, and there's nothing to do with it. * * # Building 2006-11-23 19:12 Daily opencode[ Unregistered user]http://ajax.asp.net/docs/tutorials/e15e7ffb-e4b2-4a89-b99e-16624a5861d0.aspx
The original is this. Reply Reference #11 floor 2006-12-14 11:14 batista[unregistered user] can run? No problem. Reply Reference #12 building 2006-12-20 15:43 Anthan If you are customizing exception handling in client script, do you need to scriptmanager1_asyncpostbackerror the processing in this one?
In addition, my side of the dead is not to show from the definition of the alert window, just display a line of text, the IDE is not displayed in the design.
And also shows the server-side exception handling support (0) against (0) reply reference #13 Lou [landlord] 2006-12-23 16:38 Terrylee @Anthan
Yes, that's the way to catch an exception in that method and handle the exception.

Which version are you using? Support (0) objection (0) Reply quote #14 building 2006-12-24 17:07 Loyalty Pig (dansinge) put onclick= "return Alertdiv_onclick ()"
Change to onclick= "return Togglealertdiv (' hidden ')"
It's OK. Support (0) objection (0) Reply reference #15 building 2006-12-24 17:19 qqwwee[Unregistered User] example no problem.

The <script> script is placed behind the ScriptManager control, or it will be the alert of JavaScript.

Spent a lot of time to study this, the script can not be placed in Thank you!! It's finally OK.
In the IE7, add:
var Abutton = $get (' OKButton ');
adiv.style.visibility = visstring;
Otherwise the okbutton will always show. Support (0) objection (0) reply quoting #17 building 2007-03-23 16:14 flapping Street Aberdeen [unregistered users] just wondering why the script must be placed behind the ScriptManager example to succeed.
Can you explain?? Reply Reference #18 building 2007-03-29 19:52 james[unregistered user] in the first example, there is a mistake in!throw ex;
Change to Label1.Text = ("You entered the wrong"); Reply Reference #19 building 2007-04-04 17:03 rongjun[unregistered user]var Adiv = $get (Divelem);
adiv.style.visibility = visstring;
May I ask what these two are for??????????????

I looked at the code, my understanding is to control <div id= "Alertmessage" > whether the display
So I replaced the two lines above.
document.getElementById ("Alertmessage"). style.visibility=visstring
But there is no error message showing ...
Is that what I think is wrong??

What's the effect of these two sentences, please?

Reply Reference #20 building 2007-04-04 17:13 rongjun[unregistered user] Sorry, just carefully and looked again, the original I think is right, but the name is wrong
No:
document.getElementById ("Alertmessage"). style.visibility=visstring
But:
document.getElementById ("AlertDiv"). style.visibility=visstring

Oh!!!!!!!!!!!!!

Very like Terrylee article, if Terrylee can write NHibernate from the introduction to proficient series, hehe!!!!!!!!!!!!!!!!
Reply to references #21 building 2007-05-28 15:29 sum up [unregistered users] comprehensive to the wrong solution for the man, finally debugging success, here to summarize:
1, in <body> plus id= "Bodytag"
2, put onclick= "return Alertdiv_onclick ()"
Change to onclick= "return Togglealertdiv (' hidden ')"
3, put the script behind the ScriptManager.  Reply Reference #22 floor 2007-07-03 17:52 yyc[unregistered user]alert or pop up, first pop alert, and then show the hidden Div, if it does not pop alert? Reply Reference #23 floor 2007-07-03 17:55 yyc[unregistered user] Sorry to be mistaken, I wrote the alert, hehe reply reference #24 building 2007-07-04 09:39 qingyun163[unregistered users] @qqwwee
Brother, we are not very familiar with JS Ah, of course, can be placed in the
<title> using client-side scripting for UpdateProgress programming </title>
<style type= "Text/css" >
#UpdatePanel1 {width:200px; height:100px;border:1px solid Gray;}
#UpdateProgress1 {width:200px; Background-color: #FFC080; bottom:0%; left:0px; position:absolute;}
</style>
<script type= "Text/javascript" >
var prm,postbackelement;
Window.onload = function () {
PRM = Sys.WebForms.PageRequestManager.getInstance ();
Prm.add_initializerequest (initializerequest);
Prm.add_endrequest (endreuqest);
}

function initializerequest (Sender,args) {
if (Prm.get_isinasyncpostback ()) {
Args.set_cancel (TRUE);
}

postBackElement = Args.get_postbackelement ();

if (postbackelement.id = = "Panel1Trigger") {
document.getElementById ("UpdateProgress1"). Style.display = "block";
}
}

function Endreuqest (Sender,args) {
if (postbackelement.id = = "Panel1Trigger") {
document.getElementById ("UpdateProgress1"). Style.display = "None";
}
}

function Cancelasyncpostback () {
if (Prm.get_isinasyncpostback ())
Prm.abortpostback ();
}
</script>

There's not a single mistake ... Reply Reference #25 floor 2007-07-04 09:49 qingyun163[unregistered user] <title> custom exception handling </title>
<style type= "Text/css" >
#UpdatePanel1 {width:200px; height:50px;border:solid 1px Gray;}
#AlertDiv {left:40%; top:40%;p osition:absolute; width:200px;padding:12px; border: #000000 1px solid;background-color: White text-align:left;visibility:hidden;z-index:99;}
#AlertButtons {position:absolute; right:5%; bottom:5%;}
</style>
<script type= "Text/javascript" >
Window.onload = function () {
Sys.WebForms.PageRequestManager.getInstance (). Add_endrequest (Endrequesthandler);
}

function Endrequesthandler (Sender,args) {
if (args.get_error () = ' undefind ') {
var errormessage;
if (Args.get_response (). get_StatusCode () = = "200") {
ErrorMessage = Args.get_error (). Message;
}else{
ErrorMessage = "An unspecified error occurred.";
}

Args.set_errorhandled (TRUE);
Togglealertdiv (' visible ');
document.getElementById ("Alertmessage"). InnerHTML = errormessage;
}
}

function Togglealertdiv (visstring) {
if (visstring = = "hidden")
Document.body.style.backgroundColor = "";
Else
Document.body.style.backgroundColor = "Gray";

document.getElementById ("AlertDiv"). style.visibility = visstring;
}

function Clearerrorstate () {
document.getElementById ("Alertmessage"). InnerHTML = ';
Togglealertdiv (' hidden ');
}
</script> Reply Quote #26 building 2008-02-25 14:16 Shun z[unregistered user] because putting the script inside the head causes SYS error ...  Put it behind the ScriptManager and there's no mistake ... Reply Reference #27 building 2008-02-29 11:14 liaobing[unregistered user] I'm the same as the 12 floor, I've never been in contact with Ajax exception handling, and now I'm in the learning stage, Terrylee's article is very good
I do not know how to debug to show, I now play out or server-side exception processing Ah, the client's cue box at all did not come out, I hope to point out. Reply Reference #28 floor 2008-06-30 22:12 veinyf#163.com[unregistered user]--reference--------------------------------------------------
Liaobing: I am the same as the 12 floor situation, has never been in contact with the Ajax exception handling, is now in the learning phase, Terrylee article is very good
I do not know how to debug to show, I now play out or server-side exception processing Ah, the client's cue box at all did not come out, I hope to point out.
--------------------------------------------------------


Prove that the client did not "intercept" the server code
Client-side code does not work. Reply Reference #29 Building 2008-07-01 16:21 anxious people [unregistered users]throw ex. where is the old newspaper abnormal Ah.
It's just a step out. What's going on? Reply reference #30 building 2008-08-13 01:48 thomaschen--citation--------------------------------------------------
Anxious person: Throw ex. How the old newspaper abnormal Ah.
<br> is a step out. What the hell is going on?
<br>
--------------------------------------------------------
I think it's the most likely version.
I am just installing the ASP. 2.0 AJAX Support (0) against (0) reply quoted #31 Lou 2008-08-13 11:05 Thomaschen landlord please ask the next inside with a bit more JS syntax should be ASP.
Where can I get this syntax?
such as args.set_errorhandled (true);

Are there any other grammatical or functional features other than the one you applied? Support (0) objection (0) reply quoted #32 building [landlord] 2008-08-13 21:38 Terrylee @thomaschen
It's not a grammar, it's just a function.

Specific you can view the relevant SDK support (0) against (0) reply to reference #33 building 2008-12-31 00:27 lost Stars [unregistered users]@ anxious people
is to throw an exception ah.
Throw it out and you can catch it.

You do not use debugging mode to start the program AH.
You can use the ctrl+f5 ... Reply Reference #34 floor 2009-02-11 10:19 mechecksv[unregistered user] page dimmed
Text can still be entered.
How to control all elements are not operational???
The gray section covers all text parts or highlights!!
Can I just click on the section of the message layer? Reply Reference #35 building 2009-03-21 12:49 a PO found that Giri is a loyal user of Microsoft products. Always feel that some controls make it uncomfortable, the function of Ajax to write more convenient ha, but still support Giri. Support (0) objection (0) Reply quote #36 building 2011-12-27 16:43 Autumn Birch Summary of the quote : Integrated to the wrong solution for the man, finally debugging success, here to summarize:
<br>1, in <body> plus id= "Bodytag"
<br>2, put onclick= "return Alertdiv_onclick ()"
<br> change to onclick= "return Togglealertdiv (' hidden ')"
<br>3, put the script behind the ScriptManager.
The onclick= "return Alertdiv_onclick ()" can be removed as normal operation support (0) against (0) reply to reference #37 building 2012-11-27 15:36 Snow White Fox First example how no alert effect

ASP. NET AJAX Starter Series (8): Custom Exception Handling

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.