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.
Spring provides two approaches for handling these exceptions: Using XML configuration: this is similar to exception handling in Servlet/JSP, by declaring a SimpleMappingExceptionResolverbean in Spring's application context file and map exception types with view names.
@ExceptionHandler annotation provided by Spring Boot can be used to handle exceptions in particular Handler classes or Handler methods. Any method annotated with this is automatically recognized by Spring Configuration as an Exception Handler Method.
Another way to handle controller level exceptions is by overriding the OnException() method in the controller class. This method handles all your unhandled errors with error code 500. It allows you to log an exception and redirect to the specific view. It does not require to enable the <customErrors> config in web.
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.
I would say best practice would be to use @ExceptionHandler. As the downside to handling the exception in the controller method is that it makes the code less readable and might be repeated across many controller methods.
I would recommend having a base class for your controllers with the @ExceptionHandler defined. This way it can be used for many different controllers, without any code duplication. This would be more readable than the exception resolver approach, but could be used in conjunction.
Service class can/should throw exception.. You can handle those exception in controller for logging purpose..also you can show appropriate error pages on the basis of exception caught on controller..but that will be tedious.. better try spring exception handling..http://www.mkyong.com/spring-mvc/spring-mvc-exception-handling-example/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With