Catching TransactionRolledbackLocalException in Java - java

I receive javax.ejb.TransactionRolledbackLocalException in Websphere 7 from the container and I wonder how is it possible to catch this exception? I have a timeout set in Websphere and get this message after this time. I run session beans.
I am trying to find what SQl statement was the cause of this exception. Where can i find that?

As per Sun's docs
Here's the bottom line guideline: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.
TransactionRolledbackLocalException is an unchecked exception and there is nothing you can do if it happens. You could catch it as Aaron Digulla suggests in his answer, but what is the point ?
If you catch it then you will be messing with the internals of the App Server. You will get an exception on the client and you can call getCause() on the exception you get on the client to properly notify the user.
You have two solutions
Look at what is causing the timeout
(Probably bad SQL)
Increase the timeout

A transaction is rolled back when one of two conditions are met:
There is an exception in your code
There is a timeout
Obviously, you can catch the exception in case #1 by wrapping the outermost code with a try{}catch(). But which code of yours is executed on timeout?
Unless your app server offers an API to attach a listener to such events, this is not possible. See the documentation which you received with the product or call the support for details.
[EDIT] If you want to see the SQL which actually causes the timeout, you have two options:
You can use java.sql.DriverManager.setLogWriter(w); to log all SQL statements to a file. While this always works, it will create a lot of output and it will be hard to match this against the exception unless you can make sure you are the only one running requests.
If you use an OR mapper (like Hibernate and such), you can enable logging for them. See here for Hibernate.

You can use also the [Log4JDBC] (https://code.google.com/p/log4jdbc/).
This allows for logging in front of the driver.
The way it works is that you specify it in the datasource like a proxy.
Of course that if you are using hibernate it is simpler to set the show sql property.
But if you use JDBC this will work because all query's go through here.

Related

Java: Call method on all caught exceptions [duplicate]

This question already has answers here:
Java: Global Exception Handler
(6 answers)
Closed 8 years ago.
I know I can set my own UncaughtExceptionHandler to execute code on uncaught exceptions, but is there a way to have some code execute on all caught exception without having to call that method in every single try-catch block?
My custom code sends me an email with the stack trace on uncaught exceptions. I also want that email for caught exception but I don't want to track down every single try-catch statement and add it.
I'm not looking for a global exception handler (I mentioned UncaughtExceptionHandler), I'm looking for a global CAUGHT exception handler.
You can do it by altering the Exception class to record every Exception. This can be done by changing the boot class path, runtime code injection or using the JVMTI.
I suspect it's a bad idea as the system will catch more exception than you might expect. You could get thousands of emails a second if something goes wrong.
I suggest you revisit your exceptions handling policy and strategy. When an exception happens it generally means something went wrong, i.e., something exceptional (as in unexpected) happened in the code (database connection lost, file not found, network unreachable, etc.) or a bug in the code causes an unexpected problem (NPE comes to mind...). In these scenarios the normal program flow can't continue.
It's usually considered best practice to fail fast in such cases, unless you are expecting some exception to be thrown and know how to recover, i.e., the exceptional condition wasn't that exceptional after all.
If you need to fail fast, you don't need to explicitly handle the exceptions as your thread or program will just die and you can just use the UncaughtExceptionHandler to log the stack trace, send emails or notifications etc.
Situation in which you can successfully recover and resume the normal program flow are far less common in my opinion and usually do not require developers/ops to be notified as it is part of the normal functioning of the system (otherwise you would not be able to handle the exception). So simply logging the specific message and useful data associated to this scenario is usually enough, e.g., "WARNING: Transient error x was recovered. State was y and z.".

how to stop specific exceptions from being logged onto the server

I am new to JBoss. As part of My Application I am using JBoss.We are also using EJB's as a part of the project also. A exception like StaleObjectStateException is raised . So , the EJB uses this exception to rollback a transaction. So, Please tell me how to stop StaleObjectStateException from being logged.Log4j is used here.
StaleObjectStateException being a runtime exception, shouldn't be caught in normal cases
But the only way for you to stop it from coming to logs, is to catch the exception in your code and eat up.
However, IMHO it should be of prime importance to figure out why you are getting this exception.
org.hibernate.StaleObjectStateException is a Hibernate exception that usually indicates that some other thread of control has updated the state of your entity bean in the database.
You must catch it before it is thrown from an EJB and deal with it somehow.
Any RuntimeException that is thrown from an EJB call automatically results in transaction rollback.
You should also read the javadoc for org.hibernate.StaleStateException to ensure that some of the other scenarios it describes do not apply to you.

Hibernate Doesn't Flush Fast Enough to Catch DB Exceptions

I have a method, inside a Try/Catch block, which calls a Hibernate DB Save operation to insert a row.
The method completes successfully even though there are DB problems (e.g. when I insert a NULL into a non-NULL column). Then, at some later point, Hibernates attempts to "flush" or complete the transaction, and that's when errors get thrown.
This messes up the flow of my code because I depend on my method completing successfully to do other things, e.g. send out emails. After calling my method, I go on to send out emails based on the assumption that no errors have happened (otherwise I would have been thrown out of my code flow and into my Catch block, but this is not happening).
Does anyone have any ideas how to deal with this situation?
The trivial answer is to simply call Session.flush() and any pending SQL will get run, causing any SQL exceptions that might be lurking to happen at that time.
On a sort of larger scope, you may want to look at options for validating your data at the application level, rather than relying on SQL exceptions to detect errors. There are up and downsides to either way of course.

Should I factor out error reporting in catch statements by re-throwing errors?

I have an error/exception that is thrown by a particular method. Any time this error occurs, I want to log it. Would it be good practice to log the error within the initial method, and then re-throw it? That way I would not need to log it in the catch statements of any function that calls this method.
It would look something like this:
public void doSomething() throws Exception{
try{
someFunction(); // throws Exception
} catch (Exception e){
logger.fatal(e.getMessage()); // always log this Excpetion
throw e;
}
}
My concern was the re-throwing of exact same error. I have not seen this done, and I wondered if it would be considered bad practice.
EDIT: I should add that this Exception should never ever happen. That might help understand this situation.
I would log information describing why your method is about to throw an exception rather than the exception itself. Let clients decide if they want to log the exception itself or handle it.
If you handle the exception I'm not sure it is the right thing to always log it. Depends on your application of course but in general it seems to me like it should be up to the client code to log the exception.
Thus, my recommendation, if the method throws the exception, let the client take care of the handling, even if it most often means logging it. (Unless of course you want the logging to be a documented side effect of the method.)
It really depends on your logging preferences. For example you database access layer may have a method that takes a SQL query as a String as an argument and executes it in the DB. Now you may want to log any SQLException in that layer and then wrap the SQLException by a custom exception [like a DatabaseException] and then re-throw it back to the parent layer. You may also want to encapsulate some additional behaviour like a boolean shouldRetry in your DatabaseException object so that the parent layer may retry the operation again. Logging the SQLException right away will let you debug the issue more easily later.
EDIT:
This approach makes more sense when your parent layer does an operation that might throw more than one kind of exception. For example, in the above scenario, the method that takes the SQL query might also throw a InvalidHostException if the database manager is unreachable or a ConnectionRefusedException, if the database manager refused connection due to overload. In such a case you might log the exception and then wrap it with the more general DatabaseException. Also if the method threw a ConnectionRefusedException then you might want to set the shouldRetry variable to true; while the same will be false for a InvalidHostException. This allows the caller API to try to call the method again after sometime if the value of shouldRetry was set to true.
NOTE: Except SQLException, the rest are creations of my imagination. :-)
I would log the error in the initial method only if there was pertinent information there that would not be available in the client code.
Maybe you could use aspect approach. So after each busines method you check the exception type that has been thrown and verify whether it matches criteria of exception that should be logged. If so you log it and rethrow exception otherwise you just rethrow exception without logging. This allow you to centralize your error logging and disable/enable it when necessary apart from business logic - this is typical cross-cutting concern not core concern.
public class MyLoggerInterceptor ... {
#AroundInvoke
public Object invoke(InvocationContext ic){
try{
ic.proceed();
}catch(Exception e){
if(exceptionShouldBeLogged(e)){
logger.fatal(e);
}
throw e;
}
}
}
There are already a lot of answers but I would say that you need to make the best decision with the information you have at the time, but you then need to monitor what you are logging when your application runs. (many developers don't do this, me included)
If you think your logging is to verbose change it and if you find that trying to investigate an issue you don't have enough information then you add more logging in.
Its like method naming, its difficult to get right the first time but keep changing until you get it perfect.

How are un-checked exceptions reported to the user

Since there is no need to try/catch or specify un-checked exceptions, how are they are reported to the user?
how are they are reported to the user?
What is the best practice to handle
un-checked exceptions?
In our application, we barely use any exception at all: neither checked nor unchecked (we consider checked exceptions to be a Java idiosynchrasy unrelated to the problem domain we're dealing with, so we wrap most checked exceptions inside cleaner APIs, using state testing methods).
The way we deal with it is simple: it's a desktop application, if we catch an uncaught exception, we offer the user the possibility to send us a report. All the user has to do is click on "Report" and we get the full stack traces and other infos sent to one of our servers.
You can set up an application-wide uncaught exception handler like this:
Thread.setDefaultUncaughtExceptionHandler( new Thread.UncaughtExceptionHandler() {
public void uncaughtException( final Thread t, final Throwable e ) {
...
// Here we offer our user the possibility to 'report' the exception, YMMV
}
}
Typically there are zero exception happening in our software: we don't use checked exception for flow control (unless when we're using brain-dead APIs from the nineties, where this was common practice).
Some frameworks, like Spring, also have a pretty strong preference towards the "no checked exceptions" mentality.
So exceptions for us are really exceptionnal, hence the popup warning the user that the app crashed and offering them the possibility to send us the report.
If you are writing a container or a framework or a UI framework, then the best place to handle them is centrally, propagate them all the way to central handler and report the error to user in a usable way,
If using a UI, provide a way for user to report that exception.
Details:
We generally use a practice when using UI is that have a central exception handler.
In case of a web UI, we have on handler that shows the user that something has gone wrong in the system, The error page also has a form with hidden fields that has stack trace along with a description (optional) field asking the user to describe what she/he was doing when error occured. The for submits the error information, with stacktrace to the system (which can be a mail or simply stored in db)
In a desktop UI, could be the same, only thing that will be different is where you put your exception handling code.
Error reporting example
Error reporting example http://www.flickr.com/photos/aniketn/4785197367/
You actually can catch unchecked exceptions. It's just that they're usually things you can't solve when you do catch them - for example, NullPointerException. There's generally not a way to smoothly and gracefully resume whatever you were doing when the NullPointerException occurred.
If you don't handle them, they will propagate all the way up through your program and it will abort, dumping a stack trace of the exception.
The best practice is to deal with the ones where you can provide some better handling than the default. For example, if you call an external library function, you could wrap it in a try/catch block and if the library throws a NullPointerException you could give the user a friendly error message (a GUI "library X failed to do Y - did you specify a valid Z?") instead of a stack trace on the command line. But in the general case, the reason they're unchecked is because even if you knew about them, there'd be nothing for it but to throw up your hands.
When bubbling out of the main(...) method, the JVM prints the stack trace to System.out and exits that thread. For single-thread programs, that would also exit the program.
In general, every thread you run should have a wrapper catching Throwable so you can at least log it to your files.

Categories