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:
And call it like this:
EDIT: with a parameter (example, can run in a console program):
For more info you can take a look at this thread.