How to throw new exception in FirstChanceException event

1

I am trialling the FirstChangeException event handler for the service layer of my WCF. The aim is to capture the exception from any method and throw it as a new FaultException so it can pass back to the client.

For example below is a test server class

private static bool thrown;
public class EchoService : _BaseService, IEchoService
{
    public EchoService()
    {
        AppDomain.CurrentDomain.FirstChanceException += HandleFirstChanceException;
    }

    private void HandleFirstChanceException(object sender, FirstChanceExceptionEventArgs e)
    {
        if (thrown == false)
        {
            thrown = true;
            throw new FaultException<Exception>(e.Exception);
        } 
    }

    public DTO_Echo_Response SendEcho(DTO_Echo_Request request)
    {
        DTO_Echo_Response response = new DTO_Echo_Response();

        //SO note: AppError inherits from Exception.
        if (request.ThrowTestException) throw new AppError("Throwing test exception");

        return response;
    }
}

However, on exiting the function on the return line because the previous call was from the throwing the new exception, I get the following error.

The runtime has encountered a fatal error. The address of the error was at 0x750916ed, on thread 0x1d5c. The error code is 0x80131506. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.

I must be doing something stupid. How can I achieve my aim of a catch all exception handler?

c#
exception
exception-handling
first-chance-exception
asked on Stack Overflow Jul 2, 2014 by Valamas • edited Jul 2, 2014 by Valamas

1 Answer

2

You are using the FirstChanceException Event here, which is just a notification, not a place to handle exceptions.

What you probably want is both of

Application.ThreadException
AppDomain.CurrentDomain.UnhandledException

There are already lots of questions on that topic.

Just have a look here on ThreadException

Also investigate on

Application.SetUnhandledExceptionMode

Exception handling in WCF is explained here:

handling exceptions in WCF right

WCF exceptionn handling

answered on Stack Overflow Jul 2, 2014 by Mare Infinitus • edited May 23, 2017 by Community

User contributions licensed under CC BY-SA 3.0