Would like to ask you a best practice question where a spring-mvc controller is concerned. Please review the code below:
@Autowired
SomeService service;
@RequestMapping (...)
public @ResponseBody Response createSomething () {
try {
serviceResponse = service.doSomething();
//create a success response and return
}
catch (SomeServiceException e) {
//create an error response and return
}
}
Is the error handling to be done at the controller level normal practice? Or should the service class not be throwing exceptions like shown above. Please review and let me know.
I would say you have three strategies depending on your use case.
There are roughly three strategies: HandlerExceptionResolver, @ExceptionHandler and handling exceptions internally within action.
The use cases for these are: common exception handler for whole application, whole controller, specific action accordingly.