如何:使用 SubCode 属性捕获错误代码

上次修改时间: 2010年5月1日

适用范围: SharePoint Server 2010

Excel Services 基于 Excel Services 中发生的错误在 SOAP 异常中生成错误。为了使开发人员能够更容易地捕获特定的错误条件,Excel Calculation Services 警报具有关联的错误代码。然后,Excel Web Services 使用 SoapException 类中的属性返回错误。

下面的示例说明如何使用 SoapException 类的 SubCode 属性 (https://msdn.microsoft.com/zh-cn/library/system.web.services.protocols.soapexception.subcode.aspx)(该链接可能指向英文页面) 捕获错误代码。

备注

为了能够使用 SubCode 属性,必须使用 Microsoft Visual Studio 2005。在 Visual Studio 的早期版本中不存在 SubCode 属性。

有关错误代码的列表,请参阅Excel Services 错误代码

使用 SOAP 捕获错误代码

  1. 在将 Web 引用添加到 Excel Web Services 之后,使用指令添加以下内容,以便您可以使用 SoapException 类,而无须使用完全命名空间对它进行限定。

    using System.Web.Services.Protocols;
    
    Imports System.Web.Services.Protocols
    
  2. 要使用 SubCode 属性捕获 Excel Services 错误代码,必须使用 SOAP12 协议版本。在实例化 Excel Web Services 代理类之后,按如下所示设置 SOAP 协议版本:

    // Instantiate the Web service. 
     ExcelService xlservice = new ExcelService();
    
    // Set the SOAP protocol version.           
    xlservice.SoapVersion = SoapProtocolVersion.Soap12;
    
    ' Instantiate the Web service. 
     Dim xlservice As New ExcelService()
    
    ' Set the SOAP protocol version.           
    xlservice.SoapVersion = SoapProtocolVersion.Soap12
    
  3. 要使用 SubCode 属性捕获错误代码,请在代码中添加一个 SOAP 异常 catch 块,例如:

    catch (SoapException e)
    {
        Console.WriteLine("SOAP Exception Message: {0}", e.Message);
        Console.WriteLine("SOAP Exception Error Code: {0}", 
            e.SubCode.Code.Name);
    }
    
    Catch e As SoapException
        Console.WriteLine("SOAP Exception Message: {0}", e.Message)
        Console.WriteLine("SOAP Exception Error Code: {0}", e.SubCode.Code.Name)
    End Try
    

使用直接链接捕获错误代码

  1. 在直接链接方案中,不必向 Excel Web Services 中添加 Web 引用。但是,您需要添加对 System.Web.Services 命名空间的引用。

  2. 添加引用之后, 将下面的 using 指令添加到代码中,以便您可以使用 SoapException 类,而无须使用完全命名空间对它进行限定:

    using System.Web.Services.Protocols;
    
    Imports System.Web.Services.Protocols
    
  3. 与使用通过 HTTP 的 SOAP 不同,在直接链接方案中,您不必设置 SOAP 协议版本。

  4. 要使用 SubCode 属性捕获错误代码,请在代码中添加一个 SOAP 异常 catch 块,例如:

    catch (SoapException e)
    {
        Console.WriteLine("SOAP Exception Message: {0}", e.Message);
        Console.WriteLine("SOAP Exception Error Code: {0}", 
            e.SubCode.Code.Name);
    }
    
    Catch e As SoapException
        Console.WriteLine("SOAP Exception Message: {0}", e.Message)
        Console.WriteLine("SOAP Exception Error Code: {0}", e.SubCode.Code.Name)
    End Try
    

示例

下面的程序(控制台应用程序)使用 SubCode 属性来捕获错误代码。该程序根据所捕获的错误代码执行不同的操作。例如,您可以有意地传递一个不存在的工作表名称来触发 SOAP 异常。在这种情况下,将返回下面的 SOAP 异常消息:

The sheet that was requested could not be found. Please try a different one.
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Services.Protocols;
using System.Threading;
using SubCodeExample;

namespace SubCodeExample
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length != 3)
            {
                Console.WriteLine("This program requires 3 parameters - 
                    workbook, sheet and cell");
            }
            string workbookUrl = args[0];
            string sheetName = args[1];
            string cellRange = args[2];

            const string DataRefreshError = 
                "ExternalDataRefreshFailed";
            const string InvalidSheetNameError = "InvalidSheetName";
            const string FileOpenNotFound = "FileOpenNotFound";

            string sessionId = null;
            MyXlServices.ExcelService service = null;
            try
            {
                MyXlServices.Status[] status;
                service = new 
                    SubCodeExample.MyXlServices.ExcelService();
                service.SoapVersion = SoapProtocolVersion.Soap12;
                service.Credentials = 
                    System.Net.CredentialCache.DefaultCredentials;
                sessionId = service.OpenWorkbook(workbookUrl, "", "", 
                    out status);

                object result = service.GetCellA1(sessionId, sheetName, 
                    cellRange, true, out status);
                Console.WriteLine("GetCell result was:{0}", result);

                int retries = 3;
                while (retries > 0)
                {
                    try
                    {
                        service.Refresh(sessionId, "");
                    }
                    catch (SoapException soapException)
                    {
                        bool rethrow = true;
                        if (soapException.SubCode.Code.Name == 
                            DataRefreshError)
                        {
                            if (retries > 1)
                            {
                                Console.WriteLine("Error when 
                                    refreshing. Retrying...");
                                Thread.Sleep(5000);
                                rethrow = false;
                            }
                        }
                        if (rethrow) throw;
                    }
                    retries--;
                }
                
            }
            catch (SoapException exception)
            {
                string subCode = exception.SubCode.Code.Name;
                if (subCode == FileOpenNotFound)
                {
                    Console.WriteLine("The workbook could not be found. 
                        Change the first argument to be 
                        a valid file name.");
                }
                else if (subCode == DataRefreshError)
                {
                    Console.WriteLine("Could not refresh 
                        the workbook.");
                }
                else if (subCode == InvalidSheetNameError)
                {
                    Console.WriteLine("The sheet that was requested 
                        could not be found. Please try 
                        a different one.");
                }
                else
                {
                    Console.WriteLine("Unknown error code returned from 
                        Excel Services:{0}", subCode);
                }
            }
            
            catch (Exception)
            {
                Console.WriteLine("Unknown exception was raised.");
            }
            finally
            {
                if (service != null && 
                    !String.IsNullOrEmpty(sessionId))
                {
                    try
                    {
                        service.CloseWorkbook(sessionId);
                    }
                    catch
                    {
                    }
                }
            }
        }
    }
}
Imports System
Imports System.Collections.Generic
Imports System.Text
Imports System.Web.Services.Protocols
Imports System.Threading
Imports SubCodeExample

Namespace SubCodeExample
    Friend Class Program
        Shared Sub Main(ByVal args() As String)
            If args.Length <> 3 Then
                Console.WriteLine("This program requires 3 parameters - workbook, sheet and cell")
            End If
            Dim workbookUrl As String = args(0)
            Dim sheetName As String = args(1)
            Dim cellRange As String = args(2)

            Const DataRefreshError As String = "ExternalDataRefreshFailed"
            Const InvalidSheetNameError As String = "InvalidSheetName"
            Const FileOpenNotFound As String = "FileOpenNotFound"

            Dim sessionId As String = Nothing
            Dim service As MyXlServices.ExcelService = Nothing
            Try
                Dim status() As MyXlServices.Status
                service = New SubCodeExample.MyXlServices.ExcelService()
                service.SoapVersion = SoapProtocolVersion.Soap12
                service.Credentials = System.Net.CredentialCache.DefaultCredentials
                sessionId = service.OpenWorkbook(workbookUrl, "", "", status)

                Dim result As Object = service.GetCellA1(sessionId, sheetName, cellRange, True, status)
                Console.WriteLine("GetCell result was:{0}", result)

                Dim retries As Integer = 3
                Do While retries > 0
                    Try
                        service.Refresh(sessionId, "")
                    Catch soapException As SoapException
                        Dim rethrow As Boolean = True
                        If soapException.SubCode.Code.Name = DataRefreshError Then
                            If retries > 1 Then
                                Console.WriteLine("Error when refreshing. Retrying...")
                                Thread.Sleep(5000)
                                rethrow = False
                            End If
                        End If
                        If rethrow Then
                            Throw
                        End If
                    End Try
                    retries -= 1
                Loop

            Catch exception As SoapException
                Dim subCode As String = exception.SubCode.Code.Name
                If subCode = FileOpenNotFound Then
                    Console.WriteLine("The workbook could not be found. Change the first argument to be a valid file name.")
                ElseIf subCode = DataRefreshError Then
                    Console.WriteLine("Could not refresh the workbook.")
                ElseIf subCode = InvalidSheetNameError Then
                    Console.WriteLine("The sheet that was requested could not be found. Please try a different one.")
                Else
                    Console.WriteLine("Unknown error code returned from Excel Services:{0}", subCode)
                End If

            Catch e1 As Exception
                Console.WriteLine("Unknown exception was raised.")
            Finally
                If service IsNot Nothing AndAlso (Not String.IsNullOrEmpty(sessionId)) Then
                    Try
                        service.CloseWorkbook(sessionId)
                    Catch
                    End Try
                End If
            End Try
        End Sub
    End Class
End Namespace

强大的编程功能

请确保将 Web 引用添加到您具有访问权限的 Excel Web Services 网站。将 using SubCodeExample; 语句更改为指向您所引用的 Web 服务网站。

此外,对工作簿路径、工作表名称等进行相应的更改。

请参阅

任务

演练:使用 Excel Web Services 开发自定义应用程序

如何:捕获异常

如何:信任一个位置

如何:从 Excel 客户端保存到服务器

概念

访问 SOAP API

Excel Services 警报

Excel Services 已知问题和提示

环回 SOAP 调用和直接链接