简体   繁体   English

WCF 用户代码未处理的异常

[英]WCF unhandled exception by user code

I'm developing a WCF service with C# and .NET Framework 4.0.我正在使用 C# 和 .NET Framework 4.0 开发 WCF 服务。

I have the following code:我有以下代码:

public long CreateUser(string userName)
{
    try
    {
        if ((userName == null) ||
            (userName.Equals(string.Empty)))
            throw new ArgumentNullException();

        ...

    }
    catch (Exception ex)
    {
        resultCode = 3;
        throw ex;
    }

    ...

}

when userName == string.Empty debugger stops and a dialog said:当 userName == string.Empty 调试器停止并且对话框说:

ArgumentNullException unhandled by user code.

How can I fix that?我该如何解决?

UPDATE更新

I want to notify client that there was an error in server side.我想通知客户端服务器端出现错误。

You need to handle the exception when using the CreateUser method:使用 CreateUser 方法时需要处理异常:

try
{
    myClass.CreateUser (user);

}
catch (ArgumentNullException ex)
{

}

I think it would be best to just do something like this at the top of your method rather than create and throw an exception.我认为最好在方法的顶部做这样的事情,而不是创建并抛出异常。

if (string.IsNullOrEmpty(userName))
{
  //handle
}

I think String.IsNullOrEmpty() is the most clear way;我认为 String.IsNullOrEmpty() 是最清晰的方法; but I'm not sure I understand the question.但我不确定我是否理解这个问题。

Your IF is working;您的 IF 正在工作; and your code is throwing the exception.并且您的代码正在引发异常。 So writting it with String.IsnullOrEmpty() won't change that.所以用 String.IsnullOrEmpty() 写它不会改变这一点。

Do you want to know how to 'handle' that exception?您想知道如何“处理”该异常吗?

If you want to notify the client use FaultException .如果你想通知客户端使用FaultException

Handle the exception:-)处理异常:-)

This is normal behavior.这是正常行为。

Your client must call your method like so:您的客户必须像这样调用您的方法:

try {
   long result = myService.CreateUser(someVariable);
} catch (ArgumentNullException exc)
{
  // Your error-handling code here
}

If you don't want to handle the exception, but simply process the "error code" (which is a bad practice, definitely not recommended), then you should remove the "throw ex;"如果您不想处理异常,而只是处理“错误代码”(这是一种不好的做法,绝对不推荐),那么您应该删除“throw ex;” line from your code.从你的代码行。

First, you should know about String.IsNullOrEmpty(), it's useful in the case you provided.首先,您应该了解 String.IsNullOrEmpty(),它在您提供的情况下很有用。

Second, you are throwing an exception up the stack.其次,您正在向堆栈抛出异常。 There needs to be a try/catch block further up that is catching the exception you're throwing.需要有一个 try/catch 块来捕获你抛出的异常。 Here, the try/catch is doing you no good.在这里,try/catch 对你没有好处。

public long CreateUser(string userName)
{
        if (String.IsNullOrEmpty(userName))
            throw new ArgumentNullException();

        ...
}

then elsewhere,然后在别处,

try 
{
     someClass.CreateUser(userName);
}
catch (ArgumentNullException ex)
{
  ... error handling code here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM