I am confused with the following question:
You are implementing a model component. You realize that an IOException might arise if you lose connection to the database. Following are the option:
Implement multipathing to provide redundant connectivity to the database, thereby avoiding that risk of connection failure.
Provide an error handler page, and use the page directive in the invoking ISP to redirect to that page if the error arises.
Use the JSTL tag to take control if the exception arises.
Surround the problem area with a try/catch block and implement appropriate recovery or fallback behavior.
I think answer is option no 4 but it's written answer is 3 i don't know how?
IMO, the assumption is once an IOException is thrown, there is no way to reconnect to the database, hence you are left with JSTL, the view component, to display the appropriate error message.
Related
After reading a lot about the abusive use of exceptions in Java and how you should let an exception bubble up through the different layers of an application, I've come to a point where I don't know what I am supposed to do with the potential errors my application can have.
Basically, I have a webservice which uses the DAO pattern to access data in my database. All of the database actions can throw a SQLException.
As of today, I'm using a try catch to catch the SQLException and then thow a specific defined exception called ExceptionDAO that will be handle by the webservice to return a correct message to the users (a mobile application) of my webservice.
After reading a lot about how exception should be exceptional and should not be used in control flow, I've come up with a mixed understanding of what I should do to handle any errors:
Use return codes for anything that is likely to happen (e.g. username already exists) and therefore, to comply with the DAO pattern, pass my business objects as parameters instead. I could also use a specific pair which would return the code + the business object instead. The webservice would then use the return code to display a specific message.
Use checked exceptions for anything that I can't predict will happen and let them bubble up to the webservice to handle and return a message to the users. (e.g. SQLException that I can't predict : connection aborted)
Let unchecked exceptions bubble up aswell and display a sort of 404 error in this case.
I also had a look at the null pattern but I don't think it suits this particular situation really well.
I'm also concerned to not give too much information to the users, but rather useful and straight to the point information. Indeed, the messages returned by the webservice will be used by a mobile application to then display a message to the end-user.
I hope that I was clear enough about the problem I'm having, and I'm looking forward to your answers !
Return codes are suitable for C, which lacks exception handling among its features. For Java, please use exceptions, either checked or runtime, that's a matter of taste.
Personally, I hate checked exceptions, because they pollute my method signatures with information of border cases that might never occur. But maybe you want to be strict with the contract of your classes, even for such exceptional cases. If that's your case, then use checked exceptions. Otherwise, let your method signatures in peace and throw a runtime exception whenever you detect an exceptional case (such as an entity not found, entity already exists, etc).
Please note that ExceptionDAO is not a happy name. It appears to be a dao that handles exceptions. Maybe something like PersistenceException would be better.
Apart from that naming detail, I think your approach is on the right way, though not ideal. Ideally, you wouldn't need to do a try/catch for SQLExceptions inside every method that calls methods from your DAOs (or inside every method of your DAOs). Instead, a persistence exception translation mechanism would be much better. Spring, for instance, comes with one by default. Spring accomplishes this by proxying every DAO, and by letting its proxies perform a try/catch around every method invocation. Then, specific SQLExceptions with specific SQL error codes are translated to Spring's own DataAccessException hierarchy. So, in the upper layers, you would end up with a specific DataAccessException, but you wouldn't need to do a try/catch inside every method.
If you are already using Spring, then you have nothing to do, but if you aren't using it and have either many DAOs or many methods that might throw SQLExceptions, and all your DAOs implement an interface, then it might be worth the effort to implement a proxy that intercepts all the methods of your DAOs and performs a try/catch around them. Then, in this interceptor's catch block, you'd throw your ExceptionDAO (please rename it!) with a message that would depend on the original SQLException (and maybe on its SQL error code, too).
This approach has the advantage that you could handle all persistence exceptions in a single point of your program.
This very same concept could be applied to your web layer as well. Instead of letting every method of your endpoints handle your ExceptionDAO (don't forget to rename it!), you could create a proxy that intercepts every method call and perform a try/catch around it. You could then extract the message from the exception and send it in the response (or whatever you find suitable to do with it). Again, this is all based in Spring, this time, in Spring MVC Exception Handling mechanism. Here you could also handle unexpected exceptions, i.e. RuntimeExceptions and provide an appropriate message to your users.
The advantage, again, would be that you could handle all the exceptions that reached your web layer in a single point of your program.
Please see Proxy javadocs and this tutorial for further reference on Java's proxies.
I think you are missing an important option, which is the observer pattern.
In your DAO you can have this:
public interface OnExceptionInteractionListener {
public void onExceptionInteraction(String exceptionMessage);
}
I would have the DAO be something like:
public SomeDAO(OnExceptionInteractionListener listener, ...) {
}
and I would instantiate the DAO as
SomeDAO s = new SomeDAO(new OnExceptionInteractionListener() {
public void onExceptionInteraction(String exceptionMessage) {
}
}, ...);
So, if there is an exception caught then call the listener in the DAO and the next level up will handle it.
This is better performance than throwing exceptions, and better than return codes.
For more on this you can look at this answer, for other examples: https://stackoverflow.com/a/18585099/67566
I haven't tried it but I expect that lambda expressions would be useful for this also, if you are using Java8.
Return codes are very old-school. Ideally, you should do your insert in some sort of transaction that checks:
Lock username inserts
Is this username available?
3a. If so, insert and unlock
3b. If not, unlock and inform user
If that's not possible, then a return object wrapping the result if it was created successfully and response Enum with potential outcomes.
I am developing a J2EE website for a mini project, and I’m puzzled about exception handling. I have defined several custom exception classes, and they’re thrown from several parts of the website, and they are captured in a custom exception handler. But, i am yet to find a good way to map the occurred Exception to an error message.
To put it simply, if an exception occurs somewhere, I have a global exception handler which captures the thrown exception ( i won't swallow it within a local catch block ), but i need an efficient mechanism by which i should be able to convert it into a suitable error message to be displayed to the end users.
Also, the custom exceptions have a tree hierarchy , which means the top of the tree will have general exceptions and the leaves of the tree would have exceptions defined for a very specific purpose.
The tree would be like
CustomException
Type1Exception
Type11Exception
Type12Exception
Type121Exception
Type122Exception
Type13Exception
Type2Exception
Type21Exception
Type211Exception
Type22Exception
Type3Exception
Type31Exception
Type32Exception
Type33Exception
Type4Exception
Type41Exception
Type411Exception
Type4111Exception
Type4112Exception
Type421Exception
Type4211Exception
Type42Exception
Each exception branch would represent exceptions occurring in specific part of the website. The tree will grow more in future, if more features are added to the website What is the best practice to map the bunch of exceptions to error messages ?
And, is using instanceOf operator and isInstance() method , to check the type of exception, a good practice (in aspects of performance ,scalability and code standards) ?
Each exception branch would represent exceptions occurring in specific
part of the website.
But what if the exception happens in a common component shared by different parts of the website?
Exceptions already tell you where they happened (that's what the stacktrace is for), you don't need to put it in the name. The name is for the reason of the exception (such as IllegalArgumentException or EOFException.
Your design is poor in many ways. You should handle exceptions where you can, either locally with a specific error message (if let's say a user wants to pick a username that's already taken) or globally with a general error message.
Edit:
There are thousands of potential error situations in an application. You can divide them into categories based on what you can do to them. Let's say you try to insert a duplicate username into the database, and an exception is thrown. You catch this and tell the user to choose a different username.
That's the least exceptional case, you might even bypass this by checking if the username exists, instead of relying on an exception.
Then you have a bit more exceptional, let's say you can't connect to the database at all. You don't know why, but you're still prepared, you tell the user that something is wrong with the database, and please try again.
Then you have the most exceptional. You're not prepared for it, you don't have a catch clause for it, it flies up to the global exception handler. All you can do is show the user a generic error message that "Something went wrong", log the error, and notify the maintenance team.
Now the way to design exceptions is based on how much information you know about what happened. You might have a DatabaseException class for all DB related errors, and a DuplicateUserException that extends it to provide more detail. Also note that a DuplicateUserException would never propagate up to a global exception handler. You'd handle it right there, showing the user the screen with the error message. The error message which you'd get from a resource bundle not with the name of the exception, but a general key, such as "exception.user.duplicate".
I think your basic mistake is thinking that you can create a single place responsible for exception handling, just based on the exception type. I suggest that you let that idea go. The global handler should only handle (mainly log) the exception when nobody else will.
I would like to access all the Synchronization's that were added to an exchange during a camel route.
The reason for this is that when a particular type of exception happens, I want to route the message to an error handling component and let that error handling component execute the "onCompletion" of those synchronizations even though there was an exception.
the synchronizations are added by using
exchange.getUnitofWork().addSynchronization(new MySyncAdapter());
and I was trying to access them with
exchange.handoverCompletions();
However, I think I must be doing something wrong because no matter which component I try to get the completions from (my real component, or the error component), the list is null.
Edit:
According tot he answer below, this should work:
exchange.addOnCompletion(new MySyncAdapter());
List<Synchronization> syncs = exchange.handoverCompletions();
however, syncs is still null. Any suggestions?
The Exchange in this case does not have the Completions/Synchronizations, the UnitOfWork instance does so when you call exchange.handoverCompletions() you will get a null. You also do not have access to the synchronizations in the UnitOfWork because it is being handled in a different thread. Any attempt to modify them, which is what handoverCompletion does, causes a concurrency exception.
In reality you are trying to use something in a way it wasn't intended. Exchange errors should be handled by invoking the Exception Clause DSL outlined here. It is designed to capture exchange errors in a fine grained manner by allowing a developer to define the Exception type and forward the Exchange to a route for further processing by your error handling component.
Best Regards,
Scott ES
For example: we have WebApplication based on MVC. Also, for this app we are used: Spring, Struts 2 and Hibernate frameworks.
Lets go look on small scenario: user try save some instanse, for example: BO Book.
So, user fill form fields and send request to the server:
What happened on server?
Execute action method Action.Save();
Inside Action.Save() call Service.save();
Inside Service.save() call DaoHibernate.save();
Inside DaoHibernate.save() call getHibernateTemplate().save();
Method getHibernateTemplate.save() - it is framework implementation, so we cant access to this method. We only know, that if something fail inside this method throws DataAccessException.
So, at this moment I think, how correct implement my logging and error handling?
On which level?
On Dao level? Service level?
Or on level Struts actions?
What do you think about this?
Or need on each level?
What best practices you can recommended?
Here is your architecture:
How do you want to handle the error on DAO layer? Return fake data? Empty collection? if you can't, just let the exception pop-up.
And how about handling on the service layer? You know that the database is not working, so what can you return to the Struts action? An empty result? An error object? Isn't exception an error object?
So the exception appears in the Struts action. Here you have some options. If the exception will actually tell something to the user and your GUI is prepared, you can return different view (and log the exception here).
But what if you catch a NullPointerException in Struts action? Will you handle it separately in every Struts action? No, so pass the exception even further (!)
I think you get the idea - as long as you don't know how to handle the exception (and logging is not handling), let the client clean-up the mess. Otherwise you are only hiding the problem and increasing the damages (e.g. transactions aren't rolled-back, users see incorrect results).
I would advice implementing generic exception handling mechanism which logs the exception and returns HTTP 500 to the user. Gentle error message (without stack trace) should appear and the user should be apologized. You should investigate every error that reaches this layer.
As far as I remember Struts (and virtually every web framework) has some centralized way of handling exceptions. (Struts 2 Exception Handling Docs)
I've read that wicket can't throw Checked exception. how to deal with this? What is a good way to implement exception handling in Wicket spring based application?
Mac
What do you mean, "Wicket can't throw". [citation needed] :)
Perhaps you read somewhere that wicket will not pass an exception to the servlet container in the default configuration?
I usually wrap specific components' methods with a try and change the page appropriately in catch, i.e. telling the user that something went wrong.
Update:
And also, you have the error(), warn() etc. in every Component which works with Feedback stuff. See here.