Hi,
I want to display an exception in a javascript alert and I'm rendering
that client code using
ClientScript.RegisterStartupScript(GetType(), key,
string.Format(@"<script>alert('ERROR:\r\n\r\n{0}');</script>",
ex.ToString()));
The problem is that ex.ToString() contains escape characters that not
appear literal in html.
For example:
"System.Data.SqlClient.SqlException: Cannot insert the value NULL into
column 'id_excepcion', table 'CI_Core.dbo.Tbl_GDC_Excepcion'; column
does not allow nulls. INSERT fails.\r\n at
System.Data.SqlClient.SqlConnection.OnError(SqlException exception,
Boolean breakConnection)\r\n at
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
exception, Boolean breakConnection)\r\n at
System.Data.SqlClient......"
appears in html as:
"System.Data.SqlClient.SqlException: Cannot insert the value NULL into
column 'id_excepcion', table 'CI_Core.dbo.Tbl_GDC_Excepcion'; column
does not allow nulls. INSERT fails.
at System.Data.SqlClient.SqlConnection.OnError(SqlException
exception, Boolean breakConnection)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
exception, Boolean breakConnection)
at System.Data.SqlClient......."
causing an error in the javascript alert because the line breaks.
How can i put the ex.ToString() in html as literal?
Thanks!
Alberto Poblacion - 12 Dec 2007 16:58 GMT
> I want to display an exception in a javascript alert and I'm rendering
> that client code using
[quoted text clipped - 5 lines]
> The problem is that ex.ToString() contains escape characters that not
> appear literal in html.
I pass the text of the exception through the following function, which I
don't claim to be optimal but gets the job done:
public static string EscapeText(string text)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach (char c in text)
{
int asc = Convert.ToInt32(c);
if (asc >= 0x28 && asc <= 0x5b) sb.Append(c);
else if (asc >= 0x5d && asc <= 0x7e) sb.Append(c);
else
{
string hex = string.Format("{0:x}", asc);
if (hex.Length < 2) hex = "0" + hex;
sb.AppendFormat("\\x" + hex);
}
}
return sb.ToString();
}
Lucas - 12 Dec 2007 18:37 GMT
It's a good solution, thanks!