My code has a nasty smell that looks like this:
@RequestMapping(value = { "/updateGraph" }, method = RequestMethod.POST)
public ResponseEntity<ArrowsGraph> updateGraph(@RequestBody ArrowsGraph g){
try{
g = arrowsBo.updateGraph(g);
return new ResponseEntity<ArrowsGraph>(g, HttpStatus.OK);
} catch (Exception e) {
errorLogging.logFatalException(e, sessionState);
return new ResponseEntity<ArrowsGraph>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@RequestMapping(value = { "/deleteGraph" }, method = RequestMethod.POST)
public ResponseEntity<ArrowsGraph> deleteGraph(@RequestBody ArrowsGraph g){
try{
g = arrowsBo.deleteGraph(g);
return new ResponseEntity<ArrowsGraph>(g, HttpStatus.OK);
} catch (Exception e) {
errorLogging.logFatalException(e, sessionState);
return new ResponseEntity<ArrowsGraph>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Things to mention:
- The exceptions being caught are runtime exceptions, likely thrown if the database mapping is configured incorrectly. If the code is working correctly, exceptions should never be thrown, but in the case there is an error, I want to display an error the client side, instead of having unintended behaviour.
- The reason I'm using
ResponseEntity<..>
instead of@ResponseBody
is so I can return a 500 in the case that an exception is thrown. - The purpose of
errorLogging.logFatalException(...)
is to log the error, and notify admins.
Before I refactored to use ResponseEntity<...>
and catch the runtime exceptions, the methods looked a lot cleaner:
@RequestMapping(value = { "/deleteGraph" }, method = RequestMethod.POST)
public ArrowsGraph deleteGraph(@RequestBody ArrowsGraph )
return arrowsBo.deleteGraph(g);
}
Is there a nice way to avoid this repetition/boilerplate?