2

我正在尝试使用 log4net 表达式,但它不起作用。我认为缺少一些东西,但我不知道是什么。这是我的代码:

let clusterIDArray = try
                         myfunction
                     with
                         log.Fatal("my function is not working")   


log.Debug("my function is working")

有任何想法吗?

4

2 回答 2

4

您的代码段中有两个错误:

  • 你没有执行你的功能。我想您确实在真实代码中执行了它;这是编造一个例子的问题。
  • 您没有捕获异常或您的try...with...块在语法上不正确。

假设我们在任何情况下都捕获异常并返回一个数组,一种更惯用的日志记录方式可能是:

let clusterIDArray =
    try
       let result = myfunction args // Assume args are arguments declared before
       log.Debug("my function is working")
       result
    with 
    | ex ->
       // ex is of type exception which can be parsed by log4net
       log.Fatal("my function is not working: ", ex)   
       [||]
于 2012-02-23T17:18:01.690 回答
3

如果不知道它是什么就很难说myfunction,但是当您编写它时,代码实际上并没有运行该函数。它只是将它作为一个值(来自try .. with块)返回并将其分配给该clusterIDArray值,因此代码永远不会抛出。

如果函数只需要一个unit参数,你可以try .. with像这样在块内调用它(如果它需要一些参数,你需要将它们提供给块内的函数):

let clusterIDarray = 
  try 
    myfunction ()
  with _ ->
    log.Fatal("not working")
    reraise() // You still need to return something here or rethrow the exception

log.Debug("my function is working")  

编辑正如其他人指出的那样,语法with e无效。你需要写with e ->或者with _ ->如果你想忽略异常。

于 2012-02-23T17:02:52.393 回答