I currently handle my exceptions like this:
try {
}
catch (ServiceException ex) {
ModelState.Merge(ex.Errors);
}
catch (Exception e) {
Trace.Write(e);
ModelState.AddModelError("", "Database access error: " + e.Message);
}
This works but it's the same code I repeat many times. What I am looking for is some suggestion on how I could move this into an external function. I don't necessarily need to move the try block there but at least the other code.
Maybe a function that was passed the Exception and the ModelState (as a reference). Can anyone suggest a clean way that I could code up this function. I'm asking here because almost always someone seems to come up with a solution that I could never have thought of. Thanks Samantha.
You could make a method that takes in an Action, and invokes it in a try/catch block:
private void RunAndHandleExceptions(Action action)
{
try
{
action.Invoke();
}
catch (ServiceException ex)
{
ModelState.Merge(ex.Errors);
}
catch (Exception e)
{
Trace.Write(e);
ModelState.AddModelError("", "Database access error: " + e.Message);
}
}
And call it like this:
RunAndHandleExceptions(new Action(() =>
{
//Do some computing
}));
EDIT: with a parameter (example, can run in a console program):
private static void ParameterizedTask()
{
Task.Factory.StartNew(new Action<object>((y) =>
{
Console.WriteLine(y);
}), 5);
Thread.Sleep(1500);
}
//OUTPUT: 5
For more info you can take a look at this thread.
(Updated to match the OP's new requirement in comments)
private void HandleException(Action<IEnumerable<string>> action,
IEnumerable<string> parameters)
{
try {
action(parameters);
}
catch (ServiceException ex) {
ModelState.Merge(ex.Errors);
}
catch (Exception e) {
Trace.Write(e);
ModelState.AddModelError("", "Database access error: " + e.Message);
}
}
which can be invoked with a lambda for instance:
HandleException((parameters) => Console.WriteLine(parameters.FirstOrDefault()),
new string[] {"Pretty safe in this case"});
Besides passing the the exception to another function as has been suggested in the comments, you could also pass the code to be run as an Action
to function would then run the action in a try catch.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With