I use Vaadin framework to create my web application GUI.
I have a Vaadin button and its click listener code may throw an application custom exception. In other points of application code, this exception is thrown all the way back to my custom window class, where it's centrally handled. I'd like to do something similar here: throw this exception in the clickListener code, so I could catch it in my custom terminal error handler in the window class. As the click listener class does not throw any exception, I'm unable to throw the exception there and I think I'll be obliged to handle the exception locally. As I don't want to handle the exception at the button click listener level, I think I'll forward it to my custom window class. Something like this:
Button btnNew = new Button("New", new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
try {
doThingThatThrowsException();
} catch (Exception exc) {
window.handleCustomException()
}
}
});
Is this the usual way of centralizing handling of a custom exception using Vaadin?
I can't answer as to whether it's the usual way of handling the exception, but we do something very similar.
Depending on how many listeners or how often you have to do this, you could also create abstract listeners that do that delegation for you.
e.g.
abstract class BasicListener {
protected void handleThrowable(Component.Event event, Throwable throwable) {
Window window = event.getComponent().getWindow();
if (window instanceof ExceptionHandlingWindow) {
((ExceptionHandlingWindow) window).handleException(throwable);
} else {
// Log it ? DO something, anyway.
}
}
}
abstract class ExceptionHandlingButtonClickHandler extends BasicListener implements Button.ClickListener {
#Override
public void buttonClick(Button.ClickEvent event) {
try {
handleClick(event);
} catch (Throwable e) {
handleThrowable(event, e);
}
}
protected abstract void handleClick(Button.ClickEvent event);
}
Button btnNew = new Button("New", new ExceptionHandlingButtonClickHandler() {
#Override
protected void handleClick(Button.ClickEvent event) {
doThingThatThrowsException();
}
});
Related
When Tomcat session times out, I want to redirect my user to the homepage of my GWT app, so that they can login again. To force this, I'm trying to use the StatusCodeException thrown by GWT when the user tries to perform any operation after their session times out -
SEVERE: com.google.gwt.user.client.rpc.StatusCodeException: 0
To achieve this, I'm using the following code -
public void onModuleLoad() {
GWT.UncaughtExceptionHandler uncaughtExceptionHandler = new GWT.UncaughtExceptionHandler() {
public void onUncaughtException(Throwable e) {
if (e instanceof StatusCodeException) {
logger.log(Level.ERROR, "Exception caught!");
logger.log(Level.ERROR, ((StatusCodeException) e).getStatusCode());
}
}
};
GWT.setUncaughtExceptionHandler(uncaughtExceptionHandler);
try {
// rest of the code in onModule() - I'm expecting any operation to throw StatusCodeException when session times out.
} catch (RuntimeException ex) {
uncaughtExceptionHandler.onUncaughtException(ex);
}
}
This is not working. Instead of getting caught by the code, the StatusCodeException is being displayed on the console. What am I doing wrong here?
The idea is to catch StatusCodeException and use its getStatusCode() method to find out if the HTTP error code is 403. If it is, I want to use Window.Location.assign("https://example.com/redirect"); to redirect them to a login page.
onFailure(Throwable caught) {
logger.error(caught);
}
Your AsyncCallback.onFailure is doing exactly what you asked it to do - it is logging the error, but not throwing it. Since it wasn't thrown, the uncaught exception handler doesn't handle it (it can't be not-caught, if it wasn't thrown... if that makes sense).
One option could be that you could populate the method with throw caught, but java won't like this. Instead, the easiest answer to your specific on is simply to pass it to the handler:
onFailure(Throwable caught) {
GWT.getUncaughtExceptionHandler().onUncaughtException(ex);
}
One other option you have: since no AsyncCallback will ever throw this, putting the StatusCodeException in the UncaughtExceptionHandler seems a bit odd. Instead, consider making your own AsyncCallback base class, something like this:
public abstract class NetworkAsyncCallback<T> implements AsyncCallback<T> {
#Override
public void onFailure(Throwable t) {
if (e instanceof StatusCodeException) {
logger.log(Level.ERROR, "Exception caught!");
logger.log(Level.ERROR, ((StatusCodeException) e).getStatusCode());
}
}
}
Now, when you make a call, you just have to pass in a new NetworkAsyncCallback<T> and only implement onSuccess. You can skip onFailure if all it was going to do was pass the exceptions to the uncaught handler. Or, if you have some other logic, you can override onFailure, handle the appropriate exceptions, and call super.onFailure(caught) with any other errors so that the superclass handles it.
myServer.getSomeData(param, new NetworkAsyncCallback<Result>() {
#Override
public void onSuccess(Result result) {
//...
}
// Skip onFailure, or if you need custom logic, implement it,
// and call super only if the exception isn't part of that logic
});
In an app I'm developing, I'm using Google Analytics to track uncaught exceptions like so:
// ...after setting up Google Analytics...
Thread.setDefaultUncaughtExceptionHandler(new AnalyticsExceptionHandler(Thread.getDefaultUncaughtExceptionHandler()));
And this is the handler, the AnalyticsExceptionHandler class:
public class AnalyticsExceptionHandler implements UncaughtExceptionHandler
{
// Private
private UncaughtExceptionHandler _defaultHandlerRef;
public AnalyticsExceptionHandler(UncaughtExceptionHandler defaultHandlerRef)
{
this._defaultHandlerRef = defaultHandlerRef;
}
#Override
public void uncaughtException(Thread t, Throwable e)
{
// ...track and send the exception to Google Analytics...
_defaultHandlerRef.uncaughtException(t, e);
}
}
Thing is, the app never actually crashes, it just freezes. If I remove the setDefaultUncaughtExceptionHandler() line then the app crashes normally.
Am I doing something wrong in the above code by passing it to the previous default handler?
Why not re-throw the exception?
public void uncaughtException(Thread t, Throwable e)
{
// ...track and send the exception to Google Analytics...
_defaultHandlerRef.uncaughtException(t, e);
throw e;
}
I want to install some kind of global handler to catch any ExceptionInInitializerError which could be thrown from any static block when some class is loading. Currently it dumps a stack trace to the stderr and exits the application. I want to log a stack trace using my logging framework, then exit the application. Is it possible?
It looks like Thread.UncaughtExceptionHandler is what you are looking.
This answer will provide you with more information.
In essence you need to install default exception handler as soon as possible:
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread t, Throwable e) {
if (e instanceof ExceptionInInitializerError) {
// do something with you're exception
// and than close application
System.exit(-1); // passing
}
}
});
Maybe you can make a global exception handler and just filter your exception out of it.
Example
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread t, Throwable e) {
if (e instanceof ExceptionInInitializerError) {
//Your handler code
}
}
});
I want to catch all uncaught exceptions and bring up a dialog. First I removed the default exception handler from NetBeans and added my handler as default handler:
java.util.logging.Logger global = java.util.logging.Logger.getLogger("");
for (Handler handler : global.getHandlers()) {
if (handler.getClass().getName().equals("org.netbeans.core.startup.TopLogging$LookupDel"))
{
global.removeHandler(handler);
break;
}
}
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());
The handler looks like this:
public static final class ExceptionHandler implements UncaughtExceptionHandler
{
#Override
public void uncaughtException(Thread thread, Throwable throwable)
{
logger.error(throwable.getMessage(), throwable);
ExceptionViewPanel.showException(throwable);
}
}
With that construct, I can only catch exceptions which are thrown outside the EDT. I've read about ThreadGroups, but I can't use that solution due we use NetBeans with Maven and so I can't wrap the start thread with a ThreadGroup. The hack from pre-1.7 is also no longer possible and overwriting the EventQueue has no effect.
I've tried many solutions, none of them worked. Does anyone has another solution for me that might work?
Thanks in advance
Teazl
In my own project I've superseded NetBeans error handler to my own. My example:
#ServiceProvider(service = Handler.class, supersedes = "org.netbeans.core.NbErrorManager")
public class MyHandler extends Handler {
#Override
public void publish(LogRecord record) {
if (record.getThrown() != null) {
record.getThrown(); // do with it something
}
}
#Override
public void flush() {
}
#Override
public void close() throws SecurityException {
}
}
See also org.netbeans.core.NbErrorManager and org.netbeans.core.NotifyExcPanel to know how NetBeans uses default handler.
You only need to add this class in your project.
I want to override the global Exception Handling in my RCP app. Whenever an uncaught Exception happens I want to log it (using java logging) and then exit the app. I have already overwritten the eventLoopException(Throwable exception) method in the ApplicationWorkbenchAdvisor class. But this catches only the event loop exceptions. As of now I have also overwritten the postStartup() method like this:
public void postStartup()
{
Policy.setStatusHandler(new StatusHandler()
{
#Override
public void show(IStatus status, String title)
{
LOGGER.log(Level.SEVERE, "Uncaught Exception", status.getException());
UnexpectedErrorDialog();
PlatformUI.getWorkbench().close();
}
});
}
It logs the exception in my log file and exits the app. But it's obviously not right and the exception is shown twice in the console, cause all I do is intercepting the showing of the exception in a gui dialog to the user. So how can I properly overwrite/change the global exception handling, so that my code (log) is used instead of the default one?
I would suggest you to use org.eclipse.ui.statusHandlers extension point
Thanks to sambi reddy's tip i have now overwritten AbstractStatusHandler in the ApplicationWorkbenchAdvisor class
#Override
public synchronized AbstractStatusHandler getWorkbenchErrorHandler() {
if (myStatusHandler == null) {
myStatusHandler = new MyStatusHandler();
}
return myStatusHandler;
}
MyStatusHandler extends AbstractStatusHandler and i have overwritten the handle method like this:
#Override
public void handle(StatusAdapter statusAdapter, int style)
{
if(statusAdapter.getStatus().matches(IStatus.ERROR) && ((style != StatusManager.NONE)))
{
LOGGER.log(Level.SEVERE, "Uncaught Exception", statusAdapter.getStatus().getException());
UnexpectedErrorDialog();
PlatformUI.getWorkbench().close();
}
}
seems to work right, only downside is that i still get 2 console outputs.