I have the following code:
public IDictionary<string, string> GetNextBase36(string partitionKey, string rowKey, ref string seq)
{
Sequence sequence;
try {
sequence = _sequenceRepository.Get(u => u.PartitionKey == partitionKey & u.RowKey == rowKey);
} catch {
_errors.Add("", "Database error: Get sequence failed");
}
try {
sequence.Value = Base36.Encode(Base36.Decode(sequence.Value) + 1);
_sequenceRepository.AddOrUpdate(sequence);
seq = sequence.Value;
} catch {
_errors.Add("", "Database error: Updating sequence failed");
}
return _errors;
}
It works but it seems overkill to have each database access surrounded by a try catch block. Is there some way I could simplify this? Is there any beter approach?
Updated code based on help / advice:
public IDictionary<string, string> GetNextBase36(string partitionKey, string rowKey, ref string seq)
{
Sequence sequence;
string catchMsg = string.Empty;
try {
catchMsg = "Database error: Get sequence failed"
sequence = _sequenceRepository.Get(u => u.PartitionKey == partitionKey & u.RowKey == rowKey);
sequence.Value = Base36.Encode(Base36.Decode(sequence.Value) + 1);
catchMsg = "Database error: Updating sequence failed"
_sequenceRepository.AddOrUpdate(sequence);
seq = sequence.Value;
} catch {
_errors.Add("", catchMsg);
}
return _errors;
}
You are sacrificing exact exception stack traces on the altar of error message readability (not to mention code readability).
Consider your audience: a developer. A developer should be able to read an exception stack trace, which is much more valuable debugging information than a short error message.
Hence my suggestion is to only put in one exception handler for logging somewhere higher up the hierarchy. If you have to have one in your current method, at least capture the full exception stack trace.
Also – does it really make sense to continue after the first exception? If retrieving the sequence fails, using its value in the next try block won’t fair any better. It does not make sense having multiple try/catch blocks here, unless you know exactly how to solve the problem in each catch handler so you can continue.
Update:
Now that you have a single try/catch block code readability is improved. It still looks very odd that you are basically returning a list of errors to the caller – the error case should be exceptional, so it should not bleed into the business logic of your method, instead I would just let the exception go up the stack until you can truly handle the problem (or just log it and exit the app).