All components have a built-in error indicator that can be set explicitly with setComponentError() or can be turned on implicitly if validating the component fails. As with component caption, the placement of the indicator is managed by the layout in which the component is contained. Usually, the error indicator is placed right of the caption text. Hovering the mouse pointer over the field displays the error message.

The following example shows how you can set the component error explicitly. The example essentially validates field value without using an actual validator.

// Create a field.
final TextField textfield = new TextField("Enter code");
main.addComponent(textfield);

// Let the component error be initially clear.
textfield.setComponentError(null); // (actually the default)

// Have a button right of the field (and align it properly).
final Button button = new Button("Ok!");
main.addComponent(button);
((VerticalLayout)main.getLayout())
        .setComponentAlignment(button, Alignment.BOTTOM_LEFT);

// Handle button clicks
button.addListener(new Button.ClickListener() {
    public void buttonClick(ClickEvent event) {
        // If the field value is bad, set its error.
        // (Allow only alphanumeric characters.)
        if (! ((String) textfield.getValue()).matches("^\\w*$")) {
            // Put the component in error state and
            // set the error message.
            textfield.setComponentError(
                new UserError("Must be letters and numbers"));
        } else {
            // Otherwise clear it.
            textfield.setComponentError(null);
        }
    }
});

The Form component handles and displays also the errors of its contained fields so that it displays both the error indicator and the message in a special error indicator area. See Section 5.19, “Form and Section 5.19.3, “Validating Form Input” for details on the Form component and validation of form input.

Notifications are error or information boxes that appear typically at the center of the screen. A notification box has a caption and optional description and icon. The box stays on the screen either for a defined time or until the user clicks it. The notification type defines the default appearance and behaviour of a notification.

Notifications are always associated with a window object, which can be a child window (the positioning is always relative to the entire browser view). The Window class provides a showNotification() method for displaying notifications. The method takes the caption and an optional description and notification type as parameters. The method also accepts a notification object of type Window.Notification, as described further below.

mainwindow.showNotification("This is the caption",
                            "This is the description");

The caption and description are, by default, written on the same line. If you want to have a line break between them, use the XHTML line break markup "<br/>". You can use any XHTML markup in the caption and description of a notification. If it is possible to get the notification content from user input, you should sanitize the content carefully, as noted in Section 12.9.1, “Sanitizing User Input to Prevent Cross-Site Scripting”.

main.showNotification("This is a warning",
            "<br/>This is the <i>last</i> warning",
            Window.Notification.TYPE_WARNING_MESSAGE);

The notification type defines the overall default style and behaviour of a notification. If no notification type is given, the "humanized" type is used as the default. The notification types, listed below, are defined in the Window.Notification class.

TYPE_HUMANIZED_MESSAGE

A user-friendly message that does not annoy too much: it does not require confirmation by clicking and disappears quickly. It is centered and has a neutral gray color.

TYPE_WARNING_MESSAGE

Warnings are messages of medium importance. They are displayed with colors that are neither neutral nor too distractive. A warning is displayed for 1.5 seconds, but the user can click the message box to dismiss it. The user can continue to interact with the application while the warning is displayed.

TYPE_ERROR_MESSAGE

Error messages are notifications that require the highest user attention, with alert colors and by requiring the user to click the message to dismiss it. The error message box does not itself include an instruction to click the message, although the close box in the upper right corner indicates it visually. Unlike with other notifications, the user can not interact with the application while the error message is displayed.

TYPE_TRAY_NOTIFICATION

Tray notifications are displayed in the "system tray" area, that is, in the lower-right corner of the browser view. As they do not usually obsure any user interface, they are displayed longer than humanized or warning messages, 3 seconds by default. The user can continue to interact with the application normally while the tray notification is displayed.

All of the features of specific notification types can be controlled with the attributes of Window.Notification. You can pass an explicitly created notification object to the showNotification() method.

// Create a notification with default settings for a warning.
Window.Notification notif = new Window.Notification(
        "Be warned!",
        "This message lurks in the top-left corner!",
        Window.Notification.TYPE_WARNING_MESSAGE);

// Set the position.
notif.setPosition(Window.Notification.POSITION_TOP_LEFT);

// Let it stay there until the user clicks it
notif.setDelayMsec(-1);

// Show it in the main window.
main.showNotification(notif);

The setPosition() method allows setting the positioning of the notification. The method takes as its parameter any of the constants:

Window.Notification.POSITION_CENTERED
Window.Notification.POSITION_CENTERED_TOP
Window.Notification.POSITION_CENTERED_BOTTOM
Window.Notification.POSITION_TOP_LEFT
Window.Notification.POSITION_TOP_RIGHT
Window.Notification.POSITION_BOTTOM_LEFT
Window.Notification.POSITION_BOTTOM_RIGHT

The setDelayMSec() allows you to set the time in milliseconds for how long the notification is displayed. Parameter value -1 means that the message is displayed until the user clicks the message box. It also prevents interaction with other parts of the application window, as is default behaviour for error messages. It does not, however, add a close box that the error notification has.

System messages are notifications that indicate a major invalid state in an application that usually requires restarting the application. Session timeout is perhaps the most typical such state.

System messages are strings managed in SystemMessages class.

sessionExpired

Application servlet session expired. A session expires if no server requests are made during the session timeout period. The session timeout can be configured with the session-timeout parameter in web.xml, as described in Section 4.8.3, “Deployment Descriptor web.xml.

communicationErrorURL

An unspecified communication problem between the Vaadin Client-Side Engine and the application server. The server may be unavailable or there is some other problem.

authenticationError

This error occurs if 401 (Unauthorized) response to a request is received from the server.

internalError

A serious internal problem, possibly indicating a bug in Vaadin Client-Side Engine or in some custom client-side code.

outOfSync

The client-side state is invalid with respect to server-side state.

cookiesDisabled

Informs the user that cookies are disabled in the browser and the application does not work without them.

Each message has four properties: a short caption, the actual message, a URL to which to redirect after displaying the message, and property indicating whether the notification is enabled.

Additional details may be written (in English) to the debug console window described in Section 12.4, “Debug and Production Mode”.

You can override the default system messages by implementing the getSystemMessages() method in the application class. The method should return a Application.SystemMessages object. The easiest way to customize the messages is to use a CustomizedSystemMessages object as follows:

// Override the default implementation
public static SystemMessages getSystemMessages() {
    CustomizedSystemMessages messages =
            new CustomizedSystemMessages();
    messages.setSessionExpiredCaption("Ohno, session expired!");
    messages.setSessionExpiredMessage("Don't idle!");
    messages.setSessionExpiredNotificationEnabled(true);
    messages.setSessionExpiredURL("http://vaadin.com/");
    return messages;
}

Notice that the special getSystemMessages() method is not defined in an interface nor does it exist in the Application superclass.

Application development with Vaadin follows the event-driven programming model. Mouse and keyboard events in the client cause (usually higher-level) events on the server-side, which can be handled with listeners, and that is how most of the application logic works. Handling the events can result in exceptions either in the application logic or in the framework itself, but some of them may not be caught properly.

For example, in the following code excerpt, we throw an error in an event listener but do not catch it, so it falls to the framework.

final Button button = new Button ("Fail Me");

button.addListener(new Button.ClickListener() {
    public void buttonClick(ClickEvent event) {
        // Throw some exception.
        throw new RuntimeException("You can't catch this.");
    }
});

Any such exceptions that occur in the call chain, but are not caught at any other level, are eventually caught by the terminal adapter in ApplicationServlet, the lowest-level component that receives client requests. The terminal adapter passes all such caught exceptions as events to the error listener of the Application instance through the Terminal.ErrorListener interface. The Application class does not, by default, throw such exceptions forward.

The reason for this error-handling logic lies in the logic that handles component state synchronization between the client and the server. We want to handle all the serialized variable changes in the client request, because otherwise the client-side and server-side component states would become unsynchronized very easily, which could put the entire application in an invalid state.

The default implementation of the Terminal.ErrorListener interface in the Application class simply prints the error to console. It also tries to find out a component related to the error. If the exception occurred in a listener attached to a component, that component is considered as the component related to the exception. If a related component is found, the error handler sets the component error for it, the same attribute which you can set with setComponentError().

In UI, the component error is shown with a small red "!" -sign (in the default theme). If you hover the mouse pointer over it, you will see the entire backtrace of the exception in a large tooltip box, as illustrated in Figure 4.10, “Uncaught Exception in Component Error Indicator” for the above code example.


You can change the logic of handling the terminal errors easily by overriding the terminalError() method in your application class (the one that inherits Application) or by setting a custom error listener with the setErrorHandler method. You can safely discard the default handling or extend its usage with your custom error handling or logging system. In the example code below, the exceptions are also reported as notifications in the main window.

@Override
public void terminalError(Terminal.ErrorEvent event) {
    // Call the default implementation.
    super.terminalError(event);

    // Some custom behaviour.
    if (getMainWindow() != null) {
        getMainWindow().showNotification(
                "An unchecked exception occured!",
                event.getThrowable().toString(),
                Notification.TYPE_ERROR_MESSAGE);
    }
}

Handling other exceptions works in the usual way for Java Servlets. Uncaught exceptions are finally caught and handled by the application server.