Is there anyway to handle SQL Error other than try catch block in spring boot? - spring-boot

In Spring Boot in #ControllerAdvice error handler, we can provide Exceptions & what to do for the following. But, it doesn't work with Error.
DataIntegrityViolationException ca handle some SQL errors like more length, duplicate, etc.
But, some errors come under SQLError.
I tried adding SqlError.class, Error.class. But, it didn't capture as it handles only Exception
#ExceptionHandler
Temporarily, I am handling it in a try-catch block. And, if not handled without try-catch also fine, but it gives query result in REST response saying this field this error, etc. Which is vulnerable to show to the user.
So, if it can be handled globally, we will just avoid those parts.

Related

Handling expected exceptions from dao

I am currently coding a spring-mvc (jsp) project with three layers (controller -> service -> dao) and I am wondering what is the correct way of handling expected exceptions from dao invocations (e.g trying to persist an User that already exists, if it exists then call the register view again with a message saying that the user already exists), at first I thought it would be a good idea to catch the exception in the dao (e.g DataIntegrityViolationException) and throw my arbitrary checked exception so then I can do an exception handler for it in the controller but I fear if I do this then I might have conflicts if I want to make my service methods #Transactional later on since spring won't know how to rollback the transaction.
If this is correct then I have two ideas:
try/catch DataAccessException in the controller when I invoke the service call userService.register(..)
Use something among the lines like userService.findByUsername(username) in the controller (which returns an Optional) and if its present I notify the user before even calling userService.register(..)
Also, our teacher emphasizes on following DDD behavior and trying to avoid leaking business logic in our controllers and I fear both of this solutions do that but I don't really know how to handle it otherwise.
Spring already converts checked JDBC exceptions into more informative unchecked exceptions, which play well with service layer transactions. All your custom checked exceptions do is force you to type more. Spring gives you reasonable defaults, take advantage of them.
Create an exception handler. Spring has multiple ways to implement this, none of them involve writing catch blocks for exceptions in your controller.
Put the business logic in the service, not the controller. It seems like your findByUsername and register can be combined in one transactional service method.

Difference between try catch and #ExceptionHandler in Spring REST

I was going through a video tutorial where the instructor focussed on handling any Runtime exceptions through the #ExceptionHandler in Spring.
What is the difference between the approach of handling it via try catch or via #ExceptionHandler?Which is the better approach and when to use either of them?
bro we use #ExceptionHandler above a method which we want to handle all the exception that occurs in your code while in case of try and catch you just handle the exception where it occurs only. But if we want that every exception that occurs in our program to be handled by one method, so that it will look clean and professional, we use #ExceptionHandler. Here is the link that might help you understand this.
https://howtodoinjava.com/spring-core/spring-exceptionhandler-annotation/
Let me know if this helps.

How can I handle Tomcat's MaxUploadSizeExceededException in Spring?

I have done some research around this with conflicting results. To handle this error, some say that I need to implement HandlerExceptionResolver in one of my controllers.
Here are some links for that:
How to handle MaxUploadSizeExceededException
Handling MaxUploadSizeExceededException with Spring MVC
http://www.raistudies.com/spring/spring-mvc/file-upload-spring-mvc-annotation/
On the other hand, other people are saying that this approach is futile such that the Exception is occuring outside the request handling flow:
http://forum.spring.io/forum/spring-projects/web/124409-handling-maxuploadsizeexceededexception-in-spring (The second poster in the thread)
MaxUploadSizeExceededException doesn't invoke the exception handling method in Spring
I have tried the above solutions but they do not work for me. It appears that the Exception occurs outside of Spring, as expected. I am unable to catch this even with HandlerExceptionResolver.
Trying following the approach specified in the link below. Basically, you configure an error page for any un handled exception and then define a handler for the error page. Looks like a decent workaround.
Here is the link http://www.javacodegeeks.com/2013/11/how-to-custom-error-pages-in-tomcat-with-spring-mvc.html
Hope this helps.

Handling exception when using HibernateDaoSupport

I am using Spring Hibernate integration in my application and DAO classes are extending HibernateDaoSupport.
Suppose I save some object using the code
getHibernateTemplate().save(object);
As Spring Hibernate integration doesn't mandate to write try-catch block, but suppose if any exception is thwron while saving that object.
Then what is the best way to handle it? I means should I catch it in the service layer and wrap it in some user defined excpetions.
Do I need to write try-catch in DAO layer method itself in case I want to log which method in DAO throws exception?
I have never used HibernateDaoSupport or Hibernate Template before so ignorant about exception handling. Please provide me your valuable inputs
The idea behind Spring using RuntimeException is that generally there are different types of exception:
Exceptions that you want to recover from (such as a DuplicateKeyException if a record that you're trying to insert already exists or the more general DataIntegrityViolationException if there was a DB constraint that was violated as a result of user input)
Exceptions that you can't recover from (the database is down)
For the first case, you may well handle the exception (either through a custom business exception, so that the view layer can redirect to the input page and provide a meaningful message)
For the second case, it would be easier to let the exception bubble up and have it handled by a generic exception handler that then displays a generic error page to the user. For this scenario it doesn't make sense to wrap the exception in a custom exception as you won't be able to recover. A blown up DB tends to be fatal.
So what I would do:
try {
getHibernateTemplate().save(object);
} catch (DataIntegrityViolationException dive) {
throw new BusinessValidationException(dive, "You've got the data wrong");
}
Spring exception hierarchy is well documented.
Usually you can't do much if you have a data access exception, because in the working system this may be caused by the shortage of diskspace on the DB server, or network connection problems etc.
Such exceptions are usually need to be logged and investigated as soon as possible.
There some recoverable errors, they can be handled with spring exception hierarchy, but imho most of them should be avoided during the developing phase, so your web server should validate as many things as possible, before it goes to the db.
If you want to set the exception logging see the similar questions:
Exception handler in Spring MVC
Spring MVC Best Practice Handling Unrecoverable Exceptions In Controller

How to configure spring HandlerExceptionResolver to handle NullPointerException thrown in jsp?

From a jsp is thrown a NullPointerException for example using <% null.toString(); %>
This exception is not handled by the HandlerExceptionResolver, but thrown to the web container(tomcat) and converted into a code 500 error.
How can I configure spring to get that error in my HandlerExceptionResolver ?
Details:
Spring can be configured to handle exceptions thrown inside Controllers, but not exceptions thrown by view.
Of course i can resolve the NullPointerException, but i want to design a solution that will gracefully resolve any possible problem on the web application in order to display a user friendly message to the user.
See the HandlerInterceptor interface instead. You'll want the afterCompletion method. You can then intercept the response and then set the appropriate header information to redirect to a container-configured error web page. You're right that Spring doesn't have this functionality, this is going to have to be specified by the web.xml which determines which codes map to which pages.
I have not worked with this particular bit of the spring framework, but the docs say
"Interface to be implemented by objects than can resolve exceptions thrown during handler mapping or execution, in the typical case to error views. Implementors are typically registered as beans in the application context.
Error views are analogous to the error page JSPs, but can be used with any kind of exception including any checked exception, with potentially fine-granular mappings for specific handlers."
so I'd imagine that given that NullPointer extends RuntimeException the framework isn't designed to catch it. Is there a reason the exception(s) can't be handled in the controller directly?

Resources