How to catch a runtime exception in a NB platform module? - java

As described here, I want to update the user's database by means of catching the exception that occurs when the entity classes don't match. I understand that I could add a catch statement to every db-interface method, but that's error-prone*. Other 'polling methods' are also possible, but they are not interrupt-driven as I want through catching exceptions.
I think what I'm looking for is to catch the exception before it's delivered to the user (possibly to crash the application). I would put there my catch block. I'd have put it in the main() in a non NB app.
My understanding is that the exception is thrown on an entity basis (i.e. a method that involves only one entity, which has not changed, will not throw any exceptions, although other entities have changed).

I had a similar problem, but I guess mine is a bit harder to solve. I use JPA at server side, and the server is actually a webservice provider.
The persistence is managed by the container, and according to my app settings, it uses a "Create" strategy. Of course, every time I change my entities and redeploy the application it throws a lot of exceptions.
What I finally decided to do is to create/migrate the existing database in a separate process. This is, reading the metadata associated to the entities and comparing it with the current database.
Afterwards, it creates a migration script in case the db schema is different to fit it into the new one without losing any information (the migration script generation complexity depends on how do you plan to handle cases like data type changes or attribute removal). The last step is redeploying the app (in your case start it).
I'd suggest a proactive approach, where you don't wait for the exception to be thrown, but trying to guess the changes before to run the application.

Related

What is the possible use case for #Transactional(NEVER)

Docs state obvious thing:
a method will throw an exception if it is executed inside existent transaction.
Can anyone give a meaningful example of when/why it can be used on purpose?
Well, there may be several use cases that require your code not to run in a transaction. You'd use NEVER to enforce that as opposed to NOT_SUPPORTED which would just "suspend" the current transaction and resume it afterwards.
One use case that we had would be sending an email after some transactional operation. Sending the email itself doesn't require a transaction and to make sure the operation was successful and didn't get rolled back at the last moment our email sending service uses NEVER (otherwise we might accidentally send a "success" email and then get a rollback). That way if someone would call it while the operation's transaction still hasn't been successfully committed yet we'd get an exception and know that this should be fixed.
One use case might be framework related code that handles transactions or scopes. Think of Apache Deltaspike, arquillian, hibernate, ...
If you expose public methods you might want to make sure they are not wrongly used inside some transaction. Instead of unintentionally messing up open transactions you would rather fail-fast using #NEVER.
If you want to modify a nontransactional resource inside your code and want to make sure that others know this fact, you can use this feature.

Using exception for communication

I have heard that one should not use exception for communication.
I have a scenario that I would like to discuss.
We have a rest controller that invokes a service that is responsible for fetching a product from the database. Currently if product can't be found we will get an exception (checked exception) productNotFoundException.
This exception goes all the way to the controller. In the controller we have a controller exception handler (controller advice) that takes care of the exceptions and returns 404.
I was told that if they are run on different threads then the whole application would crash and it would be better to deal with the exception directly. Currently a lot of methods are being called and all have throws prodNotfoundex.
Can some one explain why it would crash. My project is a spring boot project.
I was told to return an empty response to the controller instead of throwing an exception.
I'm not sure how it would crash your application, if you handle/catch the exception properly.
Regarding exceptions, it should be seen as an exceptional state -- that is not in the normal flow of actions. Eg. the FileNotFoundException is exceptional, because you wanted to open the file, but it's not there. You expected it to be there, but it wasn't.
If you search for a product, you don't expect it to be there in the general sense of "expecting to find a loaf in the grocery store". You searched for a bunch of keywords, and the search resulted an empty response/zero matches. It is not exceptional in your business logic.
On the other hand, when you click "order" on a product (say on the product page), and then the product is not found, it is "exceptional". You expected a product you found 2 minutes ago to be there, but it isn't any more.
Some links on Java Exception handling costs:
http://java-performance.info/throwing-an-exception-in-java-is-very-slow/
Is it expensive to use try-catch blocks even if an exception is never thrown?
How expensive are Exceptions
How slow are Java exceptions?
Decide it for yourself.

Where can I handle Exceptions in MVC Java?

I am coding GUI application for exchange and synchronize data between company's Accounting software and e-commerce system (internet shop).
I want to create it using MVC (Model-View-Controller) Design Pattern.
Part of my application is function which overwrite e-commerce inventory balance with this from accounting software.
I've got
View - JDialog presenting progress of overwriting.
Controller - responsible for interaction between db's and view
Model - data from dbs and app's settings
When I queuing the database I must catch an exception (ClassNotFound and SQL).
Where I should create try {} catch {} block? In View? or in Controller?
I want to present some JOptionPane with error message and finish some state of application.
You have mentioned only checked exceptions.
You don't need to catch an exception. You can choose to declare it instead.
If you don't want to declare it, you can wrap it in a RuntimeException.
All exceptions from the model should be handled at a single place in code (so-called exception barrier) and presented to the Controller in a unified fashion. The Controller's main interest is whether the operation did or did not succeed, it's not interested in the fun details of why it may have failed.
Writing your DAO layer (for DB communication) without using something like Spring for declarative transactions, connection pooling, etc. is not recommended.
This is a tricky question and is going to come down to how you structure your code. Generally, if you can, have your models throw the exception in such a way that the view can handle it. This decouples you model from your view.
There are going to be occasions (such as using JTables or JLists) where this kind of thing isn't possible. In these situations, if possible, load the "model data" separately (handling any errors) and then pass it into the control (JTable/JList) models.
But again, you are probably going to run into situations where you find yourself with a standard model (such as a table model) and you are reading you data from a separate model (such as resultset or such (only an example) - because performance is improved or what ever) where the model will be presented with the task of trying to deal with the exception.
In this case, I can only suggest you provide your models with some kind of error handler/listener that is capable of reporting the errors back to the UI. If you can, us an interface, this will allow you to decouple the view/models if you need to.
Just some ideas

Always try-catch-finally for exceptions? Central error management?

I wonder if I always have to use try-catch-error blocks that clutter the code a lot, if I want to catch an error.
Or can I somehow define a global error catcher?
Especially regarding Java EE Webapps.
For every unhandled ex I'd like to log to a specific file, and display a general error page to the user.
I thought I might achieve that with aspects. But for aspects to catch on #AfterThrowing, I too have to introduce try-catch blocks. And as there is no central class for the backing-facades, I would have to surround every backing method with trycatches.
Then the aspect would take them, but I need something to catch without explicit throws exceptions.
How could I to that?
You are looking for the declare soft construct. This will wrap the given exception in a SoftException (an AspectJ-specific RuntimeException) so that it does not need to be explicitly handled. Then you can handle all of these exceptions with some AfterThrowing advice.
declare soft only exists in code style AspectJ (ie- there is no annotation for this). So, you will need to compile your code using the AspectJ compiler, but you can still use load-time weaving for this if you like.
See here:
http://www.eclipse.org/aspectj/doc/released/progguide/quick-other.html
And here:
http://www.eclipse.org/aspectj/doc/released/adk15notebook/declare-soft.html
Here's a code snippet that shows how it can be done:
aspect ErrorHandler {
declare soft : Exception : within(*);
after() throwing(Exception e) : handler(e) {
// do something...
}
}
This will route all exceptions in your system through your custom error handler. And you won't need to explicitly catch or throw them.
It's simple and powerful. Perhaps too powerful, though. I'd recommend refining and being more precise about exactly which exceptions should be softened and which ones need to be advised, but this is the basic idea.
You don't have to do this in every method.
You should not catch an exception that you can't "handle". Handling means more than just rethrowing or logging or printing a stack trace. I think handling means implementing a meaningful recovery strategy.
It might mean "the buck stops here": You're Gandalf on the bridge at the edge of a layer boundary, and no exception shall pass. You don't want users to see nasty messages, so you catch and route them to a friend, easy to understand page that tells them what to do next.
Finally isn't always necessary, but it's perfect for cleaning up resources like file handles and database cursors.
If you cannot handle an exception, there's no shame in adding the throws clause to the method signature and letting callers figure out what they want to do.
In the general case, there is no mechanism to do this - Java does not have what you're looking for.
However, depending on your circumstances, it might be possible.
web.xml Exception Handler
The web.xml file allows you to define a URL to be used to handle specified exception type. (See, for example, http://wiki.metawerx.net/wiki/Web.xml.ExceptionType).
Since you're writing a webapp, you may be able to just let the exceptions throw all the way to the top, and then handle them this way.
Custom interceptor
You mention that you have backing-facades. Depending on how they're being constructed, you may be able to put a generic proxy in front of them to catch and handle the exceptions you're interested in. You've tagged your question with spring, to you might want to look at Spring AOP Proxies.
There might be other ways to get what you want, but it will depend on the specifics of your application's architecture.
The finer control you have of the exceptions, the easier it will be to debug/provide a meaningful message.
To which extent? I would link that to the complexity / expected lifetime of your application. The bigger those are, the finer should be your handling.
I see two main approachs:
User approach: You get at least one exception handling for each UI action (so you can say: "Do not push that button AGAIN").
Debugger approach: Every method has its control.
Keep in mind that most handling could be just logging of rethrowing of the exception.
More to the point, most probably, your Java EE framework will have log options in its configuration files (many of them working with java.util.loggin or log4j). You could tweak that; of course, what is send to each log category will depend of the framework implementation (so maybe not all ERROR messages will be Exceptions).

Spring: Catch ConstraintViolationException at commit time

I'm using Hibernate and Spring and I'm currently stuck with something which I thought would be very simple to fix. I have a service method similar to this:
#Transactional
public void deleteObject(ObjectClass object)
{
this.objectClassDAO.delete(object);
}
I need to display a friendly message when the user tries to delete an object which is related to another entity. The problem I have is that the ConstraintViolationException is thrown until commit() is called, which runs outside of the scope of my service method. Is there a way to let spring call some intermediate code in the event of a particular exception, so that I can set the proper error message?
I've been searching on google for over an hour with no luck. The approaches I've found that seem at least mildly related seem like overkill and like they run at application level. Is there a simple way to intercept an exception after a commit at method-level?
You're probably using FlushMode.AUTO and the exception is being thrown when the transaction ends (in the proxy around your service created by Spring). You can explicitly call Session.flush() inside of the objectClassDAO.delete() method. You typically don't want to do this, but in this case it will force a synchronization with the underlying persistence and if there is a constraint violation the exception will be thrown before objectClassDAO.delete returns. This may be a last resort though.

Categories

Resources