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/ja-jp/library/system.web.services.protocols.soapexception.subcode.aspx) (英語) を使用してエラー コードをキャプチャする方法を示します。

注意

SubCode プロパティを使用可能にするには、Microsoft Visual Studio 2005 を使用する必要があります。SubCode プロパティは、以前のバージョンの Visual Studio にはありません。

エラー コードの一覧については、「Excel Services のエラー コード」を参照してください。

SOAP の使用時にエラー コードをキャプチャするには

  1. Excel Web Services に Web 参照を追加した後で、完全な名前空間によって修飾しなくても SoapException クラスを使用できるように、次の using ディレクティブを追加します。

    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. 参照を追加した後で、完全な名前空間によって修飾しなくても SoapException クラスを使用できるように、using ディレクティブをコードに追加します。

    using System.Web.Services.Protocols;
    
    Imports System.Web.Services.Protocols
    
  3. SOAP over HTTP を使用する場合と異なり、直接リンクのシナリオでは、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

堅牢なプログラミング

アクセス可能な Excel Web Services サイトに Web 参照が追加されていることを確認します。参照する Web サービスを指すように using SubCodeExample; ステートメントを変更します。

また、ブックのパス、シート名などを必要に応じて変更します。

関連項目

タスク

[ウォークスルー] Excel Web Services を使用してカスタム アプリケーションを開発する

[方法] 例外を検出する

[方法] 場所を信頼する

[方法] Excel クライアントからサーバーに保存する

概念

SOAP API にアクセスする

Excel Services の警告

Excel Services に関する既知の問題とヒント

ループバック SOAP 呼び出しと直接リンク