简体   繁体   中英

c# class-wide exception handling

Is it possible to catch exceptions in a single place in ac# class file?

I'm coding some unit tests in NUnit to test for a WCF Web-Service, and on all methods/tests want to trap a "EndpointNotFoundException" without having to code this for each test.

edit

I guess i wanted to create a descriptive error in this case without having to put an additional catch block in each method, as i do indeed want the test to fail.

As i've done something similar to this in WCF with the FaultException i was interested to know if it was possible in general with C# classes

But the bottom line is that if it fails, it fails! thanks to @TrueWill for stating the obvious ;) and to @Abhijeet Patel for making me think more about how i structure my unit tests

(oh, and apologies for answering my own question ;)

In general , no - you can only catch locally. There are isolated exceptions occasions when you can do this - ASP.NET MVC controllers and WCF services being two examples that leap to mind where the error handling can easily (or easily enough ) separated.

But in your case - don't you just want to add [ExpectedException(...)] to the affected tests?

Perhaps a better approach would be to look into injecting the exception handling code with AOP (postsharp) or policy injection?

AFAIK, what you are trying to do is not possible. You can look into Application.ThreadException and AppDomain.CurrentDomain.UnhandledException for centralized exception handling.

You can use AOP to achieve this. The idea is, as you request, to attach some behaviour (exception handling in this case) to all methods in the class.

For example, using PostSharp , you can define the following "exception handler":

[Serializable]
class EndpointNotFoundExceptionHandlerAspect : OnExceptionAspect
{
    public override void OnException(MethodExecutionEventArgs eventArgs)
    {
        if (eventArgs.Exception is EndpointNotFoundException)
            eventArgs.FlowBehavior = FlowBehavior.Continue; // continue without throwing an exception
        else
            base.OnException(eventArgs);
    }
}

Then add the EndpointNotFoundExceptionHandlerAspect to your class definition. Then every time the EndpointNotFoundException is thrown, it will be "handled".

Note: I make no claims that this is a good idea. This is merely an example of how it can be achieved.

可以进行面向方面的编程来处理诸如EndpointNotFoundException ..之类的单一类型的异常,并且可以使用该异常将其记录在某处。

An approach I've taken to this sort of problem is by providing an InvokeAction method which allows you to manage your exception handling in a relatively unified way. This does rely on each of your methods having a similar signature however, naturally you can provide more signatures to cover these other actions:

private void InvokeAction (Action<TData> action, data)
{
    try
    {
        action(data);
    }
    catch (EndpointNotFoundException enfe)
    {
        .... unified handling here
    }
    catch (OtherExceptionType oet)
    {
    }
}

Using this approach you can then make a call to your service methods which will all have the same try catch block invocation.

eg InvokeAction(AddUser, userData);

eg InvokeAction(UpdateUser, userData);

You'll have to create a logging mechanism (or use a third party implementation like log4net) and insert catch blocks everywhere, where the exceptions are logged. In other words, no.

As Marc already pointed out, using an [ExpectedException] on the unit test seems to be the most logical way to go especially for unit tests, where you want to focus on a unit of functionality. if you are doing a lot of try...catch style processing and conditional checking then your unit test isn't really a unit test

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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