33

分散アプリケーションを開発しています。その中には、検証する必要のある役割と権限のセットがあります。例外
をスローするのは良い習慣ですか?たとえば、不正アクセスですか? または、クライアントにメッセージを送り返す必要がありますか?

4

3 に答える 3

58

サービス操作では、次のように両方の目的に役立つFaultContractを指定できます。

[OperationContract]
[FaultContract(typeof(MyServiceFault))]
void MyServiceOperation();

MyServiceFaultは、複合型の場合と同じように、DataContract属性とDataMember属性でマークする必要があることに注意してください。

[DataContract]
public class MyServiceFault
{
    private string _message;

    public MyServiceFault(string message)
    {
        _message = message;
    }

    [DataMember]
    public string Message { get { return _message; } set { _message = value; } }
}

サービス側では、次のことができます。

throw new FaultException<MyServiceFault>(new MyServiceFault("Unauthorized Access"));

そしてクライアント側では:

try
{
    ...
}
catch (FaultException<MyServiceFault> fault)
{
    // fault.Detail.Message contains "Unauthorized Access"
}
于 2012-09-28T22:05:09.250 に答える
12

そうですね、WCFサービス実装メソッドですべての例外をキャッチし、それらをFaultExceptionsとして再スローできます。このようにすることで、選択したメッセージとともに例外がクライアントに再スローされます。

[OperationContract]
public List<Customer> GetAllCustomers()
{
    try
    {
        ... code to retrieve customers from datastore
    }
    catch (Exception ex)
    {
        // Log the exception including stacktrace
        _log.Error(ex.ToString());

        // No stacktrace to client, just message...
        throw new FaultException(ex.Message);
    }
}

予期しないエラーがクライアントに中継されないようにするために、サーバー側のコードで例外インスタンスをスローしないこともお勧めします。代わりに、1つ以上の独自の例外タイプを作成し、それらをスローします。そうすることで、予期しないサーバー処理エラーと、無効な要求などが原因でスローされるエラーを区別できます。

public List<Customer> GetAllCustomers()
{
    try
    {
        ... code to retrieve customers from datastore
    }
    catch (MyBaseException ex)
    {
         // This is an error thrown in code, don't bother logging it but relay
         // the message to the client.
         throw new FaultException(ex.Message);
    }
    catch (Exception ex)
    {
        // This is an unexpected error, we need log details for debugging
        _log.Error(ex.ToString());

        // and we don't want to reveal any details to the client
        throw new FaultException("Server processing error!");
    }
}
于 2012-09-28T22:12:25.053 に答える
3

一般的なドットネット例外をスローすると、 basicHTTPBindingを使用していない場合、サービスクライアントプロキシとサーバーチャネルが障害状態になります...これを回避するには、常にサービスからFaultExceptionをスローする必要があります...キャッチブロックから次を使用してください。

throw new FaultException("Your message to the clients");
于 2016-12-03T11:01:10.117 に答える