Another alternative is to create a method to handle the error. I'm not sure if I've written it in the correct language but you should get my drift.
Perhaps something like:
MyObject getMyObject(bool condition1) {
if (condition1) {
doSomeObjectSetup();
try {
saveObjectToDatabase()
return theObject;
} catch (ValidationException) {
// error reporting specific to exception here
}
}
// I would prefer to return an object here over throwing an exception however
// it depends on if the object is the same type as theObject? For now we will
// just throw an exception
throwBadRequestException();
}
void throwBadRequestException() {
setupError(thing);
setupError2(thing2);
// throw a custom exception
throw new BadRequestException();
}
I would probably move the displayErrorInUI() outside of this routine so that you can handle the error's it returns in different ways. Something like:
try {
bool myObject = myMethod(condition1);
// do something with myObject
}
catch(BadRequestException ex) {
displayErrorInUI();
}
If you find yourself doing this a lot then you could wrap the the call to getMyObject etc in an getMyObjectUI() or some such and passing a call back method for the do something part of it.
return;
after you throw an exception. – w0lf Apr 3 '12 at 18:27throwError()
is a terrible name for that method – w0lf Apr 3 '12 at 18:33