Suggestions for making a reusable try/catch block in C#?

后端 未结 5 1795
故里飘歌
故里飘歌 2021-01-30 09:33

I have a class that has about 20-some methods in it. Each one does some web service message processing. I just had to make a change to it, and realized that every one of these m

5条回答
  •  广开言路
    2021-01-30 10:14

    there are ways in which you can do it easily - firstly for me I have started using AOP in order to catch my exceptions

    this would effectively turn your code

    try
            {
                /* *** actual processing specific to each method goes here *** */
            }
            catch (FaultException cfex)
            {
                // common stuff
            }
            catch (CustomException cfex)
            {
                // common stuff
            }
            catch (Exception ex)
            {
                // common stuff
            }
            finally
            {
                FinalizeServiceCall(wsBus, wsMessage, response, logProps);
            }
    

    into something like

    [HandleException( Exception , FaultException, 
                          "Error Getting Details" )]
        public MYType GetDetails( string parameter )
        {
            //.... call to service
        }
    

    using Postsharp - details here

    alternatively there is a blog post by Mark Rendle on how to catch exceptions in a Functional Programming way - i have not tried this one though

提交回复
热议问题