Which example to be followed out of the following 4 examples for MVC application

Below are the couple of example of error handling throughout the MVC application using spring or spring boot.

Please validate and let me know which is the correct approach. If none of them is correct, please suggest a right approach to follow for a MVC application which has controller, service, dao layer.

Example1: Controller throws exception whichever service layer throws it

https://github.com/aasthasmile/Spring-Boot-MVC-WebBasedApplication/blob/master/src/main/java/csulb/edu/aasthajain/controller/UserController.java

Example2: Catching exception in controller and throwing Status Object at last with error message

https://github.com/SurendraVidiyala/SpringRestCrud/blob/master/src/main/java/com/javacrud/controller/RestController.java

Example3: Creating exception in Controller and throwing the exception directly

https://github.com/khoubyari/spring-boot-rest-example/blob/master/src/main/java/com/khoubyari/example/api/rest/HotelController.java

Example4: Open Source project shopizer approach. catch exception in controller layer and sets the response status

https://github.com/shopizer-ecommerce/shopizer/blob/2.0.5/sm-shop/src/main/java/com/salesmanager/shop/controller/ReferenceController.java
Software ProgrammerAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

mccarlIT Business Systems Analyst / Software DeveloperCommented:
Please validate and let me know which is the correct approach

Why do you think any one approach has to be "correct"? Just like in any piece of code, there are many ways to achieve a desired result and what works for one will not necessarily work for another.
0
Software ProgrammerAuthor Commented:
May be a suggestion or comment on each approach may be really helpful. I am just building a Spring Boot MVC application and need to follow an approach as fresh
0
girionisCommented:
As it has already been said there is no "correct" or "wrong" approach.

However my personal favourite is the second approach, catch exceptions and return an error object (with the appropriate HTTP status code). If you are building a RESTfull application it is better to not throw arbitrary exceptions from the end points. Instead catch any exceptions that might be thrown in your application and return appropriate objects with error messages in them, with the appropriate status code.

For example, do not throw a FileNotFound exception from your end-point. Instead return an error object with a 404 status code.
0
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

Software ProgrammerAuthor Commented:
How about controller advice instead of second approach ? What are the pros and cons between the two?
0
girionisCommented:
You might as well use a ControllerAdvice, it will make your code clearer. Actually this is a better approach since with a ControllerAdvice you can intercept any HTTP response statuses as well.
0
Software ProgrammerAuthor Commented:
Do you say to follow controller advice or go with second approach ? if we follow second approach we cannot handle the exception in a generic way and a generic status code to handle in the front end.

Also, do we need to introduce controller advice or exception handling so that the exception goes to application log instead of tomcat log ???

Is that is the primary reason we are going for exception handling ?
0
girionisCommented:
You can use both. You might as well do something like the following:

@ExceptionHandler(EmployeeNotFoundException.class)
	public @ResponseBody ExceptionJSONInfo handleEmployeeNotFoundException(HttpServletRequest request, Exception ex){
		
		ExceptionJSONInfo response = new ExceptionJSONInfo();
		response.setUrl(request.getRequestURL().toString());
		response.setMessage(ex.getMessage());
		
		return response;
	}

Open in new window


(taken from here)

Inside the handleEmployeeNotFoundException you might as well log the message you want.
0
Software ProgrammerAuthor Commented:
what happens if we are not doing this and the exception thrown to the ajax call directly..that's where i am unable to understand

asssume we are not handling error via controller or controller advice...what will happen in usual case..

the ajax call in front end will have success and failure...will everything cannot be handled in the front -end ...why we need this ??
0
girionisCommented:
If it is thrown directly to ajax, than it will be thrown as a 500. But ajax does not know if the 500 is a business error or an application error. If your application throws an EmployeeNotFoundException then ajax will receive 500. If you have a bug in your code and it throws a NullPointerException, ajax will again receive a 500. There is no way for ajax to know if the 500 is because of bug in your code or because of a business error.

It's not a good practice to let the front end deal with business exceptions. The backend should deal with those and return meaningful messages to ajax.
0
Software ProgrammerAuthor Commented:
Now i understand what you are saying..your explanation is good....

Can i do like this?

1. Create a mode class
2. Have three methods - one to set error message, one to set error message type (validation or data access or access denied error), one to set the response type - ERROR/EXCEPTION - ERROR is unhandled, EXCEPTION is handled, so that front-end takes the decision

If we treat ERROR and EXCEPTION are same then user cannot do anything...For ERROR we can show the message and ask the user to contact the system administrator for guidance or help to resolve. For Exception, it is business case, refer help or seek customer support for guidance.

Please let me know your views in detail
0
girionisCommented:
What is a mode class? Is it a bean? And yes you can do what you want and it is a clear solution.
0
Software ProgrammerAuthor Commented:
Model class is just a java bean or a pojo class which has few variables like response type, response status, response message....
0
girionisCommented:
Ah, ok, you mean Model, not Mode. My comments still stands, creating a model/bean is a nice way to achieve what you want.
0
Software ProgrammerAuthor Commented:
As you said an exception is thrown directly to ajax with 500 eventhough i have capture the exception in @ControllerAdvice. How to avoid it ?? What i should do in @ControllerAdvice..can u please advise with a code snippet..

Basically i want to show the error in the same page or same dialog or same window instead of throwing 500 or redirecting to the error page...
0
girionisCommented:
How to avoid it ?? What i should do in @ControllerAdvice..

You should send back the appropriate status code, by annotating with @ResponseStatus, if you do not want to return 500.


Basically i want to show the error in the same page or same dialog or same window instead of throwing 500 or redirecting to the error page...

I am not sure I understand. If you return an error response the client shouldn't redirect you, unless of course you return a ModelAndView with another page.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java EE

From novice to tech pro — start learning today.