Catch-all error handling on application level?

前端 未结 5 1924
面向向阳花
面向向阳花 2021-01-19 04:58

I have a WPF form with a couple of buttons, and for each button I have error handling code:

try {bla bla} 
catch(Exception e){
  more bla
}

5条回答
  •  不要未来只要你来
    2021-01-19 05:22

    The answer depends on your platform. In a web application you can bind the Application_Error event in Global Asax. In WCF you can inject an error handler of type System.ServiceModel.Dispatcher.IErrorHandler into the WCF stack, in forms applications you can bind the ThreadException event.

    Using it may imho be a good idea in some situations since you prevent showing exception details to the user, but also indicates a certain slobbyness regarding exception handling. I have used WCF error handlers to convert domain exceptions to http status code which is simple. Whether it is a good practice or not I do not know. For asp.net applications it is also worth looking at elmah available via NuGet.

    It is also possible to write a simple exception handler that allows you to repeat the try/catch blocks by sending reoutines as Func or Action like this

        var eh = new ExceptionHandler();
    
        eh.Process ( () => throw new SillyException());
    

    with class ExceptionHandler

        class ExceptionHandler 
        { 
            public T Process(Func func()) 
            {
               try { return func(); }
               catch(Exception ex) { // Do stuff }
            }
    
            public void Process(Action a) 
            { 
                try { action() }
                catch(Exception ex) { // Do stuff }
            }
        }
    

提交回复
热议问题