Purpose of throwing exception by Spring controller function - spring

I have come across few Spring contoller's function, which are throwing IOException.
#RequestMapping(method = ***)
#ResponseBody
public List<Offering> getOfferingDetailsList(HttpServletResponse response, #PathVariable("productIds") String productIdString, HttpServletRequest request) throws IOException
I doubt about use of such exception throwing, when no one above is catching and handling it. Is it fine to set response status like "response.setStatus(HttpStatus.SC_NOT_FOUND)" in place of throwing such exception ? What is the standard way of handling exception in controller ?

it is always good to have common exception handling functionality , so that we can make our controller code free from exception handling , by externalize to common exception handling functionality, i have come across this interesting topic for this purpose
http://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
and also use a global exception handler that will do that for all the exceptions of all the controller methods. That will centralize the exception handling, prevent massive code duplication, and avoid cluttering your controller methods.
Look at the #ControllerAdvice and #ExceptionHandler annotations.

A fairly standard way of handling exceptions in Spring Controllers is to use #ExceptionHandler.
Check out this post for more details

Related

Spring controller exception handling locally and globally

I would like some advice on how to achieve the following. I'm not providing code, as my problem is theoretical, but upon request I can. So this is the situation:
I have multiple controllers, each can throw XYException
I have a #ControllerAdvice class, in which I have an #ExceptionHandler watching for XYExceptions. When it happens, it prints out "XY".
In one (and only one) controller, when XYException is thrown, I want to do some additional task (let's say, do something that only that controller can do), and then I want the exception to be "passed on" to the global handler mentioned above.
I know I can catch the exception, do the desired task in catch block, and then re-throw the exception so the global handler can catch it, but what if I have 23 methods in the controller potentially throwing XYExceptions, and I do not want to put try-catch blocks in all 23 methods.
What is the clean Spring way of achieving this?
You could use AOP to achieve that. You'd write a method that intercepts the method inside that controller and when they throw an exception, you're aop method would run and you can do your stuff and then the exception would go in your handler class.
To achieve that you should have a class and anotate it with #Aspect and #Component
then have a method anotated with #AfterThrowing and setting the pointcut which will intercept when the given method throws an exception.
Look into Aspect Oriented Programming and Aspectj for more info.
The easy way to handle this case in ControllerAdvice is checking the stacktrace where the exception originated.
#ExceptionHandler(Exception.class)
public String handleExc(HttpServletRequest req, HttpServletResponse res, Exception e) {
if ( /*Have all null and safe check */ e.getStackTrace()[0].contains("MyController")) {
// Do your exception handling
}
}

Should I provide layer-specific exceptions in a SpringBoot backed REST Api?

I have a SpringBoot based REST Api structured as follows :
Rest Controller -> Service -> Repository
and I'm wondering how exactly to handle exceptions "properly".
For instance, let's say someone calls a /myresources/{id} endpoint with a non-existant {id}. The call gets delegated to the service which in turns tries to get the MyResource from the Repository. It fails and returns null. The Service then throws a MyResourceNotFoundException.
Now I want a specific format for my REST errors so I have a #ControllerAdvice ResponseEntityExceptionHandler which handles the custom serialization of these exceptions (#ExceptionHandler(MyResourceNotFoundException.class)).
Fine.
But this is going to result in a lot of handling/translation for each different custom exception. So I thought I could generify this by adding HttpStatus codes and messages to a base abstract exception class which MyResourceNotFound and others would extend and override. Thus the ResponseEntityExceptionHandler would simply handle building my custom error DTO in a standard way.
But then I realised that I'm adding REST concepts to an exception thrown at the service level. These shouldn't be aware of such notions...
Maybe I should catch the MyResourceNotFoundException in the Controller and throw another layer-specific exception which contains the appropriate messages and HttpStatus etc. in order to handle this generically in the ResponseEntityExceptionHandler...
What are your thoughts on this ?
You can generalize the exception as XYZMicroserviceException.
class XYZGenericException extends Exception{
String message;
custom error details....
XYZgenericException(errorMessage, custom error Details..){
this.message=errorMessage;
.......
}
}
and you can surround the suspected call which would lead to exception with try block and raise the generic exception in catch block that can be handled in global exception handler.
try{
xyz.abcMethod() // may give some exception
}
catch(Exception e){
throw new XYZGenericException(.........)
}
In the exception handler class with #restcontrolleradvice you can annotate the methods with the type of specific exception class to be handled.

Exception handling in spring

I am developing web application with spring + hibernate. As per my knowledge, it is best practice to put #transactional in service layer. Spring throws DataAccessException in case of any exception while updating data into database.
Below is my high level class structure.
#Transactional
class OrderService {
public void createOrder() {
try {
orderDAO.createOrder();
} catch (DataAccessException e) {
// convert into business exception and sends back to presentation logic.
}
}
}
What happens here is data access exception is thrown only after completion of method. so if any exception occurs, I am not able to convert it into business exception in catch block.
Work around is to flush the hibernate session in dao method but I do not like this approach. Is there any better approach to this?
I presume you are using Spring MVC, although you do not specify. If you are using Spring MVC, then there are a few different options.
You can create a Filter that looks for the DAE exception and recodes it to be a different status or exception that your front end would better understand. You can look at Spring Security's ExceptionTranslationFilter as an example of how this is already done for different exceptions
You can use a SimpleMappingExceptionResolver to map a specific exception to a particular view. This would allow your presentation layer to be agnostic and not need to know anything about the exception thrown.
You can use an #ExceptionHandler within a specific controller to handle the DAE exception in a general manner and appropriately prepare something for the presentation layer.
As an extension to #3, you can use a #ControllerAdvice to manage all DAE exceptions for any controllers in the webapp.
You can read about Exception Handling in Spring MVC for more details as well.
Generally speaking, I find that the best solution is to catch transaction exceptions at a much higher level and manipulate the information to present it to the front end in a way that is back-end agnostic. This allows you to set up your own error codes/etc. The only time I try/catch exceptions in my service itself is if I actually want to attempt a retry or modify the logic flow based on some specific exception and don't want the front end to know about it.

Spring WebMVC: interceptor which has access to the method definition and the HttpServletRequest

I'm trying to intercept Spring Controller calls which are annotated, similar to:
#RequestMapping("/my/page")
#AccessRestriction(module = Module.Audit, action = AuditActions.Log)
public ModelAndView myPage() {
// pls type teh codez
}
At this point I want to access both the values of the #AccessRestriction method, the HttpServletRequest object to check if the values match the restrictions and the HttpServletResponse object in order to send a redirect , if applicable. Being able to throw an exception might be suitable as well.
I've looked into Interceptors but they don't offer access to the method, just the handler. What are my options of achieving this?
My suggestion would be to decouple the two concerns, one to check the annotation and throw an exception, another to catch that exception and translate it into a redirect.
The first concern could be done using the Auto-proxy facility, which would apply an AOP-style interceptor to any invocations on your controller objects. They would check for the annotation, validate the invocation, and throw a custom RuntimeException is the conditions are violated.
You could then have a custom HandlerInterceptor which checked for this exception in the afterCompletion method, sending a redirect via the response object if it's present.

Spring #ExceptionHandler handling multiple kinds of exceptions

I can't figure out how to handle more than one kind of exception by #ExceptionHandler.
I need to programmatically deal with these exceptions, for this I'd need a shared reference. Is this done via this reference "Exception ex" ? I don't think so, cause the exception is not caught like this, how would I do it then ?
I can't put all the exception references as arguments to the handler method, it wouldn't make sense, it can't be programmatically dealt with. I need a shared reference so that I could use "instanceof" on it or just send it somewhere else as a general "Exception"
#ExceptionHandler({DescriptionCstOrderException.class, SpecializationCstOrderException.class, NoUploadFileException.class,
DeadLineCstOrderException.class, DocumentCstOrderException.class, CommentCstOrderException.class})
public String handleFormException(Exception ex, ActionRequest actionRequest) {
logger.error(ex.getMessage());
SessionErrors.add(actionRequest, ex.getClass().getName());
return "mainOrderForm";
}
Additional question: what if I wanted to handle org.springframework.web.multipart.MaxUploadSizeExceededException, that is not thrown from any method of the handler? Because #ExceptionHandler catches only exceptions that are thrown from one of the handler methods.
The exceptionHandler method could be placed into some extended parent controller but if one uses only defaultAnnotationHandlerMapping... ?
Appreciate any help, I'm going crazy, this is very frustrating....
The #ExceptionHandler value can be set to an array of Exception types.
The implementation of using exception array as mentioned in Spring documentation will be like:
#ExceptionHandler({
NotFoundException.class,
MissingServletRequestParameterException.class
})
The #ExceptionHandler value can be set to an array of Exception types. If an exception is thrown matches one of the types in the list, then the method annotated with the matching #ExceptionHandler will be invoked. If the annotation value is not set then the exception types listed as method arguments are used. See the documentation for details.
Your question is rather confusing but your exception handler method will only handle one exception at a time. It will not catch multiple exceptions and then pass both of them into your handleFormException() method. If you need to handle these exception types differently then you should create an exception handler method for each one, specify an argument of that specific Exception type to your method, and then do the appropriate handling. For example:
#ExceptionHandler(DescriptionCstOrderException.class)
public String handleDescriptionCstOrderException(DescriptionCstOrderException exception, ActionRequest actionRequest) {...}
#ExceptionHandler(SpecializationCstOrderException.class)
public String handleSpecializationCstOrderException(SpecializationCstOrderException exception, ActionRequest actionRequest) {...}
// and so on...
Please refer to the Spring documentation for further information:
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-exceptionhandler

Resources