In my Service classes I create an exception instance like this:
protected ServiceException _ex;
protected void Initialize()
{
_ex = new ServiceException();
}
Later in these classes I call this exception if something goes wrong:
public void Delete<T, V>(T item, V repo)
where T : Microsoft.WindowsAzure.StorageClient.TableServiceEntity
where V : IAzureTable<T>
{
try
{
repo.Delete(item);
}
catch (Exception ex)
{
_ex.Errors.Add("", "Error when deleting " + typeof(T).Name.ToLower());
throw _ex;
}
}
Outside of this in the controller I check for the exception:
catch (Exception e) { log(e); }
Then I handle this:
protected void log(Exception ex)
{
if (ex is ServiceException)
{
ModelState.Merge(((ServiceException)ex).Errors);
}
else
{
Trace.Write(ex);
ModelState.AddModelError("", "Database access error: " + ex.Message);
}
}
Sorry for the long example but what I would like to know is if this is a valid thing for me to be doing. In particular someone commented that I am creating a new value of _ex every time even if there’s no exception. Well my reason for doing this was that each controller has about twenty try-catch blocks and I thought it better to just create an _ex object at the start and so not have to have twenty areas where I create a new _ex if something goes wrong. I’d appreciate if someone could tell me if this all makes sense. Thanks.
I would suggest collecting errors in a separate structure and then just passing it in the exception class constructor whilst throw so you do not create an instance of exception class unless really need it:
BTW, can you give some examples when you track an error but do not raising an exception?