Best place to implement exception handling in spring MVC applications - spring

I am new to spring framework and wanted to know which would be the best place to implement exception handling logic - controller or service? Or if it should be done at all the layers in my code?

It is best practice to handle exceptions wherever it is encountered. If i focus on question in thread, it should be handled on both cases i.e. controller and services along with other places where there is possibility of exception.
For controller point of view i would suggest use Global Exception Handling With ControllerAdvice, even if one is using controlleradvice should also handle exception in service, utils, handlers and other classes.
Refrences: https://dzone.com/articles/global-exception-handling-with-controlleradvice

Related

What is the typical use case of Spring Application Events?

There is an amazing mechanism is spring: Spring Application Events, I see it helps to build loosely coupled application, implement observer pattern, reactor pattern.
My question is, what is the trigger in Spring application architecture when Spring Application Events is absolutely inevitable? Actually any application classes relationship can be build using events only as well as using class associations and hierarchy only (i'm talking about monolith service now).
May be it's more architectural question, but what is the threshold when it's need to consider events between objects inside a spring application?
Could it be definitely seen the cases when Spring Application Events absolutely needed?
Spring Security pushes events on certain event occurrences. See list of events
In some cases, it's much better to push message instead invoke a method in a classical way. Eg if you need to invoke the same function I multiple places in the code, just to notify another object.
It allows us to build a system which utilizes event-driven architecture. Read more
Helps in solving a producer-consumer problem
Send emails by pushing event object to ApplicationEventPublisher See Spring Higher-Order Components and #EnableEmailSending

Handle errors using a custom view

I want to handle custom errors like 401, 403, 500 etc in Spring 3.2 application using Filters . I do not want to use the web.xml approach of defining the error pages.
I tried to follow the solution listed at How to handle exceptions thrown while rendering a view in Spring MVC?
But ErrorHandler.handle does not really exist.
How can I use filters to catch all the errors and redirect to different views ?
A good way to handle exceptions in Spring Controllers is using the #ExceptionHanldler #ControllerAdvice annotations. Here is the relevant part of the documentation and here is a tutorial on their usage.

Java Server Faces: Validation only in business logic tier

I have an Java Server Faces web application and I am unsure how to handle the validation.
In my opinion the validation should be done in the bussiness logic tier. The business logic layer is used inside the web presentation (jsf) and REST-API.
At the moment i am doing also the validation inside the jsf layer with the provided validators. I think that is in the most cases only duplication of code. Is there any way to avoid this code duplication? Is java server faces able to use the validation exceptions that i am throwing inside the business logic layer?
Bean Validation has been invented for exactly this case.
You annotate your entities with constraints, and these constraints will be honoured by both your business logic (via EJB, CDI and/or JPA) as well as by JSF.
For the small amount of validations that you can't express via Bean Validation but are truly business associated; yes, throw an exception, catch it in your backing bean and set a corresponding Faces message (hint: use OmniFaces' Messages to make this easier). Equally, for the small amount of validations that you can't express with Bean Validation and which are strongly view oriented; use JSF native validators.

Centralising logging using Spring AOP

I was hoping that you guys will be able to help me with a conundrum that I am currently facing.I am currently working on an existing web application project where one of the requirements is that we have to centralise logging. The application is a layered application consisting of the client layer (i.e. the views), service layer, business layer and DAO layer.
Currently, logging in the application is handled by controller methods where each controller method that needs to have some information logged, manually logs the data by calling a logging function. Requests handled by these controller methods come from many different client sources including mobile devices (such as phones), web browsers, web services etc. Currently, all the data that needs to be logged is captured in a general purpose object which is passed to a logging method to persist these properties to a DB table.
The problem is that this general purpose object is exactly that, a general purpose object. Its used for many other tasks including logging, searching and many other tasks. When this general purpose object is used for logging, with the exception of a couple of attributes, most of the the attributes which are used to populate the general purpose object (in the case of logging) come from the request i.e. (a HttpServletRequest object). As a result of the versatility of this object, there is a potential for this general purpose object to get misused. Hence, we want to get rid of this general purpose object and create specialised objects for specialised tasks.In the case of logging, we have decided to create a logging object that we will use persist the data we need to have logged. We will be using Spring AOP effect the logging
The conundrum is this
1)Should we be using the controller to set the properties on the new specialised logging object that we want to log and then using an AOP advice, retrieve the log object for persistence once a controller method has finished executing
OR
2)should we set the properties on the new log object in an AOP advice using attributes that we have placed in a request object (i.e. HttpServletRequest object)?
My issue with option 1 is that the controller becomes aware of the logging and also, according to good design principles, a controller is only supposed to delegate tasks to business and services layers to perform such tasks. Option 1 will mean that the controller is doing more than just delegating tasks i.e. it will be building log objects
My issue with option 2 is that it couples my logging object closely with the request object (i.e. HttpServletRequest object) and hence I am wondering whether there are any potential with that approach.
Any sort of suggestions, advice and critique will be welcome. Also, if anyone has had to deal with a similar situation, I want to hear how they went about addressing the issue.
Thank you all in advance.
I'd add logging to the service layer, expressed as interfaces, using aspects.
You can use HTTP filters or aspects to log from the controller layer.
You can apply AOP in multiple layers as needed.

Spring Context Event

I am currently studying Spring.
While reading a Spring book, I met a part regarding Event.
By using context.publishEvent(..), I could trigger the event.
But I don't know what It's exactly for.
I can use other Method instead of using complicated publishEvent.
Please, tell me. thank you.
Spring Events are used to implement publish-subscribe model (or observer pattern) where two not-related parts of code must be somehow connected.
Think of the analogy of web applications where servlet container creates http sessions and your code is informed about this using javax.servlet.http.HttpSessionListener.
Spring uses this mechanism internally. It's much more visible in Spring Security where several parts of the code are informed about e.g., successfull authentication.

Resources