8

I am trying to show exception message through javascript alert box.

Here is the sample code.

public static void HandleException(Page page, Exception ex)
{
    string message = ex.Message.ToString();
    ScriptManager.RegisterClientScriptBlock(page, page.GetType(), "", "alert('"+message+"');", true);

}

It runs if i give literal values for the string variable. e.g.

string message = "Hello World";

But it fails if I give message = ex.Message;

Any Idea?

3
  • "But it fails if I give message = ex.Message;" Fails how? Commented Jun 23, 2011 at 6:42
  • I mean the alert box does not show up. It shows up only if message variable has literal string Commented Jun 23, 2011 at 6:44
  • I bet there's an error message somewhere. Check out the JavaScript console of the browser. Commented Jun 23, 2011 at 6:46

3 Answers 3

15

You need to encode it, for example using JavaScriptSerializer because if the message contains some escape characters like ' or " this will definitely break your javascript:

var message = new JavaScriptSerializer().Serialize(ex.Message.ToString());
var script = string.Format("alert({0});", message);
ScriptManager.RegisterClientScriptBlock(page, page.GetType(), "", script, true);
Sign up to request clarification or add additional context in comments.

1 Comment

I needed to modify a library function that returned the first line since the scripts were already being built on all the pages. I found trimming the quotes helpful since the Serialize adds enclosing quotes: new JavaScriptSerializer().Serialize(ex.Message.ToString()).Trim('"');
3
try    
{    
    //do some thing    
}    
catch (Exception ex)
{    
    Response.Write("<script language='javascript'>alert('" + 
        Server.HtmlEncode(ex.Message) + "')</script>");    
}

Comments

2

Does your ex.Message have any ' characters in it? They may need escaping.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.