Assuming the exception types are always the same, but the messages are different, you can do this:
static public T Try<T>(string webMessage, string soapMessage, Func<T> func) { try { return func(); } catch (WebException ex) { ErrorMessages.Add(webMessage); _logger.ErrorException(webMessage, ex); } catch (SoapException ex) { ErrorMessages.Add(soapMessage); _logger.ErrorException(soapMessage, ex); } }
This Try-method will use a delegate of type Func<T> to call the function and return its value. The function will be inside one try-catch block. Messages are provided through options. Now, somewhere else in your code, you can call it like this:
var users = Try("My web message.", "My soap message.", () => _repository.GetUsers());
Or, in your case, even shorter (if you do not use the parameters):
var users = Try("My web message.", "My soap message.", _repository.GetUsers);
Of course, you can change and arrange the Try parameters as you wish.
If you mix a method with and without return types, itβs better not to use Func , but Action . This will allow you to fulfill all situations:
static public void Try(string webMessage, string soapMessage, Action action) { try { action(); } catch (WebException ex) { ErrorMessages.Add(webMessage); _logger.ErrorException(webMessage, ex); } catch (SoapException ex) { ErrorMessages.Add(soapMessage); _logger.ErrorException(soapMessage, ex); } }
But this solution makes the code a little harder to read / maintain:
IList<User> users; Try("My web message.", "My soap message.", () => users = _repository.GetUsers());