1

I have a question regarding how exactly this thing works.

public class GlobalExceptionHandler: ExceptionHandler
{
    private string _pvtMsg;

    public override void handle(ExceptionHandlerContext context)
    {
        //few if else conditions
        if()
        {
        }
        else if
        {
            _pvtMsg = "some value";
        }
        context.Result="Some random value depending upon if else execution";
    }
}

Now when _pvtMsg is set after that, whenever exception occurs it always have that same value as before.

Does, when I set _pvtMsg = "a"; in the else if condition, the next time an error occurs _pvtMsg still have value "a"?

Is there only a single instance of handler available throughout the lifespan of my application and hence this is happening? Or are there any other reasons? Any documents for reference would be appreciated.

Btw: this handler is registered with the Register method of the WebApiConfig.

config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler()); 

1 Answer 1

3

Your assumption is correct. Since you register an Instance of GlobalExceptionHandler (with the new keyword) _pvrMsg will always have the value of the previous (successful) call.

If _pvrMsg is critical for whatever you are planning on doing in your if block, I'd recommend locking this part of the code to make sure handle doesn't execute multiple times at once.

The easiest way to do this would be:

public class GlobalExceptionHandler: ExceptionHandler
{
    private string _pvtMsg;
    private readonly object _lock = new object();

    public override void handle(ExceptionHandlerContext context)
    {
        lock(_lock)
        {
            //few if else conditions
            if()
            {
            }
            else if
            {
                _pvtMsg = "some value";
            }
            context.Result="Some random value depending upon if else execution";
        }
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Is there any other way to have new value for _pvtMsg for every exception? One way is I can reset the value during Handle method. but other than that is there any way?
The code is a bit empty, so I have no idea what you have planned for _pvtMsg.
In _pvtMsg, I'm adding some custom message in specific exception cases. that's it.
No I mean, why do you need it when handler is called again? You could just use a local variable if you just want to store some text for context.Result.
Yeah.. I guess that makes more sense :-) Thanks.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.