在 Try/Catch 块中,捕获 SoapException(任何由 XML Web services 方法引发的异常都以 SoapException 的形式引发)。
下面的代码示例是调用 XML Web services 方法的客户端捕获由 XML Web services 方法引发的异常。然后,客户端用所捕获的 SoapException 的属性填充 HTML 表。
// Create a new instance of the XML Web service proxy class.
ThrowSoapException throwSoapException = new ThrowSoapException();
// Make a call to the XML Web service method, which throws an
// exception.
try
{
throwSoapException.myThrow();
}
catch (SoapException error)
{
// Populate the table with the exception details.
ErrorTable.Rows.Add(BuildNewRow("Fault Code Namespace",
error.Code.Namespace));
ErrorTable.Rows.Add(BuildNewRow("Fault Code Name",
error.Code.Name));
ErrorTable.Rows.Add(BuildNewRow(
"Soap Actor that threw Exception", error.Actor));
ErrorTable.Rows.Add(BuildNewRow("Error Message",
error.Message));
ErrorTable.Rows.Add(BuildNewRow("Detail",
HttpUtility.HtmlEncode(error.Detail.OuterXml)));
return;
}
}
// This populates a row in an HtmlTable.
HtmlTableRow BuildNewRow(string Cell1Text, string Cell2Text) {
HtmlTableRow row = new HtmlTableRow();
HtmlTableCell cell1 = new HtmlTableCell();
HtmlTableCell cell2 = new HtmlTableCell();
//Set the contents of the two cells.
cell1.Controls.Add(new LiteralControl(Cell1Text));
//Add a cell to the row.
row.Cells.Add(cell1);