views:

81

answers:

4

i have the code...

try { do something..

    }
    catch(Exception ex)
    {
         Response.Write("<script>alert('"+ex+"')</script>");
    }

but the alert box is not displaying...

if i use the code.

    try{do some thing}

    catch (Exception ex)
    {

        Response.Write("<script>alert(\"an error occur\")</script>");
    }

alert box appears.... how could i can display the exception variable in alert box

+2  A: 

Try something like

Response.Write("<script>alert('"+ex.Message+"')</script>"); 

Have a look at the class Exception Class

astander
yaa its working... thax
Sheetal Inani
The message should be HtmlEncoded. it could contain " or other charaters that will make the html rendering behave different from the intent
Rune FS
+2  A: 

If you want to show the stacktrace:

Response.Write("<script>alert('"+ Server.HtmlEncode(ex.ToString()) + "')</script>");

or if you want only the message

Response.Write("<script>alert('"+ Server.HtmlEncode(ex.Message) + "')</script>");
Darin Dimitrov
thax.... its working
Sheetal Inani
A: 

Please check whthr you r using update panel in that page.It may sometimes work if the update panel is there.

Vishnu K B
A: 

You need to be careful and properly escape the Javascript string you are generating ... Imagine there are single quotes in the Exception's message ...

Single-quotes (') need to be escaped (\')

Response.Write("<script>alert('"+ Server.HtmlEncode(ex.Message).Replace("'","\\'" ) + "')</script>");
tsimbalar
thax... alot....
Sheetal Inani
don't forget to mark you question as answered ;-)
tsimbalar
yaa... i have marked
Sheetal Inani