19

I needed to reraise an exception that occurs while executing an async block, after logging the exception.

When I do the following the compiler thinks that I am not calling the reraise function from within the handler. What am I doing wrong?

let executeAsync context = async {
    traceContext.Properties.Add("CorrelationId", context.CorrelationId)
    try
        do! runAsync context
        return None
    with
        | e when isCriticalException(e) ->
            logCriticalException e
            reraise()
        | e ->
            logException e
            return Some(e)
}
1

4 Answers 4

19

Rough! I think this is impossible, because reraise corresponds to a special IL instruction that grabs the exception from the top of the stack, but the way async expressions are compiled into a chain of continuations, I don't think the semantics hold!

For the same reason, the following won't compile either:

try
    (null:string).ToString()
with e ->
    (fun () -> reraise())()

In these situations, where I need to handle the exception outside of the actual with body, and would like to emulate reraise (that is, preserve the stack trace of the exception), I use this solution, so all together your code would look like:

let inline reraisePreserveStackTrace (e:Exception) =
    let remoteStackTraceString = typeof<exn>.GetField("_remoteStackTraceString", BindingFlags.Instance ||| BindingFlags.NonPublic);
    remoteStackTraceString.SetValue(e, e.StackTrace + Environment.NewLine);
    raise e

let executeAsync context = async {
    traceContext.Properties.Add("CorrelationId", context.CorrelationId)
    try
        do! runAsync context
        return None
    with
        | e when isCriticalException(e) ->
            logCriticalException e
            reraisePreserveStackTrace e
        | e ->
            logException e
            return Some(e)
}

Update: .NET 4.5 introduced ExceptionDispatchInfo which may allow a cleaner implementation of reraisePreserveStackTrace above.

3
  • 1
    This answer is perhaps outdated. In .net 4.5 you can use the ExceptionDispatchInfo class, which does this and also captures Watson bucket info such as assembly of origin and IL offset. msdn.microsoft.com/en-us/library/…
    – Dax Fohl
    Commented Oct 11, 2014 at 15:10
  • 2
    @DaxFohl could please provide an updated answer using ExceptionDispatchInfo? Commented Nov 23, 2015 at 11:07
  • 5
    I have submitted this as an F# suggestion, could I have your upvotes guys? github.com/fsharp/fslang-suggestions/issues/660
    – knocte
    Commented Apr 17, 2018 at 11:10
6

As mentioned in comments and updates to answers, you can use ExceptionDispatchInfo as a workaround.

open System.Runtime.ExceptionServices

let inline reraiseAnywhere<'a> (e: exn) : 'a =
    ExceptionDispatchInfo.Capture(e).Throw()
    Unchecked.defaultof<'a>

Usage:

async {
    try
         do! someAsyncThing ()
         return "Success"
    with
    | e ->
        if errorIsOk e then return "Handled error"
        else return (reraiseAnyWhere e)
}

Here is a GitHub Gist I made with unit tests to check its behavior.

3
  • Nice solution. Just wondering why you are returning Unchecked.defaultof<'a>. And why the use of type parameters? Would it not always be returning unit?
    – slavs
    Commented Nov 17, 2022 at 6:03
  • 2
    In the example, the async block is of type Async<string> so each return expression must return a string. So reraiseAnywhere needs to be typed as returning 'a even though it never actually returns any value.
    – JamesFaix
    Commented Nov 17, 2022 at 19:34
  • nice answer! the stack trace is unchanged too
    – symbiont
    Commented Jan 21, 2023 at 0:27
5

I ran in to a similar problem, in a different context, but it boils down to this.

Exceptions cannot be thrown onto a different thread - calling reraise() would require an exception handler running in some sense 'above' the original async block in the code.

let runAsync context = async {return ()}
let isCriticalException e = true
let logCriticalException e = ()
let logException e = ()
let executeAsync context = 
    async {
            do! runAsync context
            return None
}

let run = 
    match executeAsync 5 |> Async.Catch |> Async.RunSynchronously with
    |Choice1Of2(t) -> 
        printfn "%A" t
        None
    |Choice2Of2(exn) ->  
            match exn with
            | e when isCriticalException(e) ->
                logCriticalException e
                raise (new System.Exception("See inner exception",e)) //stack trace will be lost at this point if the exn is not wrapped
            | e ->
                logException e
                Some(e)

Note, we still can't use reraise, as we are now calling on a different thread, so we wrap the exception inside another one

1
  • 1
    It's more specific then not being able to call reraise from a different thread, it can't be called from a different stackframe. Commented Aug 24, 2011 at 0:39
0

Similar to @JamesFaix''s answer...

See https://github.com/fsharp/fslang-suggestions/issues/660


Place this in an Infrastructure.fs file:

namespace global

type Exception with
    // https://github.com/fsharp/fslang-suggestions/issues/660
    member this.Reraise() =
        System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(this).Throw()
        Unchecked.defaultof<_>

Usage example:

let! client = async {
     try return! CosmosStoreClient.Connect(x, databaseId, containers)
     with e -> Log.Error(e, "Could not connect to {databaseId}/{containers}", databaseId, containers)
               return e.Reraise() }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.