简体   繁体   中英

ExceptionHandler in c# WebAPI

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()); 

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";
        }
    }
}

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