Skip to main content

Add Custom Error Handler in Vaadin 7.6

I took a small break from ADF for a month and helped a customer build their web app using Vaadin 7.6.
They had a very strick requirement on handling "unhandled exception". So I implemented something very similar to what I did for ADF last year :), but in Vaadin style.

In a nutshell :
1. Lets catch the unhandled exception.
2. Generate an unique ID for this incident and generate seaparate log file.
3. Log it with detailed stacktrace and thread dumps and other useful details(username, time etc.)
4. Save it in a specific directory.
5. Redirect the user to an Error page with the incident ID, so that user can report back to the admin people.

First of all, we need 2 classes. One singleton which does the creating incident id and logging, another session scoped bean to store the incident id which we will show the user in the Error page.

Singleton class : CustomExceptionHandler

    private static CustomExceptionHandler instance = null;

    protected
CustomExceptionHandler() {

    }

    public static
CustomExceptionHandler getInstance() {
        if (instance == null) {
            instance = new
CustomExceptionHandler();
        }
        return instance;
    }
   
    private static final ThreadLocal<IncidentContext[]> incidentContext = new ThreadLocal<IncidentContext[]>() {

        @Override
        protected IncidentContext[] initialValue() {

            return new IncidentContext[1];
        }
    };
  
    public void writeException(Throwable t) {

        IncidentContext context = incidentContext.get()[0];
        if (context == null) {
            context = new IncidentContext("No additional context");
        }

        StringBuilder incident = new StringBuilder();

        Calendar calendar = Calendar.getInstance();

        String incidentID = String.format("%s-%2$tY%2$tm%2$td_%2$tH%2$tM%2$tS", context.identification , calendar);
        String incidentFile = String.format("incident-%s.log", incidentID);

        incident.append("--------------------------------------------------------\n");
        incident.append(format(" Filename    : %s\n", incidentFile));
        incident.append(format(" User         : %s\n", VaadinSession.getCurrent().getSession().getAttribute("userName")));
        incident.append(format(" Date        : %1$tB %1$te, %1$tY\n", calendar));
        incident.append(format(" Time        : %1$tl:%1$tM:%1$tS %1$tp\n", calendar));
        incident.append("---------------------------------------------------------------\n\n");
        incident.append(format(" Unexpected error context: %s\n\n %s\n", context.text, ExceptionUtils.getFullStackTrace(t)));

        incident.append("-----------------------------------------------\n\n");
        incident.append(format(" ** THREAD DUMP:\n\n%s\n", dumpThreads()));
        incident.append("-------------------------------------------------\n");
        incident.append("[END]\n");
      
        ExceptionWriter.getCurrentInstance().setExceptionID(incidentID);
      
        String filePath = ExceptionWriter.getCurrentInstance().getFilePath();
        File f = new File(filePath, incidentFile);

        boolean traceWritten = false;
        try {
            FileOutputStream fos = new FileOutputStream(f);
            fos.write(incident.toString().getBytes());
            fos.flush();
            traceWritten = true;
        } catch (FileNotFoundException e) {     

            logger.error("The original exception was :" + incident.toString(), e);

         } catch (IOException e) {
            logger.error("The original exception was :" + incident.toString(), e);

        }
    }
    private String dumpThreads() {

        ThreadMXBean bean = ManagementFactory.getThreadMXBean();
        ThreadInfo[] infos = bean.dumpAllThreads(true, true);

        StringBuilder stack = new StringBuilder();

        for (ThreadInfo info : infos) {
            stack.append(info.toString());
        }

        return stack.toString();
    }
  
    private final static class IncidentContext {

        public static long incidentCount = 1L;

        public final String identification;
        public final String text;

        IncidentContext(Long id, String txt) {

            identification = id.toString();
            text = txt;
        }

        IncidentContext(String txt) {

            identification = String.format("#%d", incidentCount++);
            text = txt;
        }
    }


Session Scoped Bean : ExceptionWriter

    private String filePath;
    private String exceptionID;
  
    public static ExceptionWriter getCurrentInstance() {

        return (ExceptionWriter) VaadinSession.getCurrent().getSession().getAttribute("ExceptionWriter");
    }

    public String getFilePath() {
      
        filePath = getDirectory();     
      
        return filePath;
    }
   
    // Reads the folder to write the log file from web.xml context-param.
   // default folder : D://incident
    private String getDirectory() {
      
        try {
            Context env = (Context)new InitialContext().lookup("java:comp/env");
            String directoryName = (String)env.lookup("incidentFilePath");
            File theDir = new File(directoryName);
            if(theDir.exists() &&theDir.isDirectory()) {
                return directoryName;
            }
        } catch (NamingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "D://incident";
    }

    public void setExceptionID(String exceptionID) {
        this.exceptionID = exceptionID;
    }

    public String getExceptionID() {
        return exceptionID;
    }


This session  scope bean, needs to be set in the session, I initialized it in my custom VaadinServlet. 
Also, this bean reads a context param from web.xml, the folder path to put the log file. 

<env-entry>
    <env-entry-name>incidentFilePath</env-entry-name>
    <env-entry-type>java.lang.String</env-entry-type>
    <env-entry-value>/domains/vaadin_domain/incidents</env-entry-value>
 </env-entry>
  


Now we need to invoke this Exception handler from somewhere :)
Vaadin provides an excellent place for this, "setErrorHandler()" in UI class.
But we also need to redirect the user to the Error page. I created a custom layout for this, with same header and footer content as the normal web app, and with 2 custom div locations

<div location="errorContent"></div>
<div location="homepagelink"></div>


Now in your custom UI class : call the below method from init()

private void setErrorHandler() {
      
        UI.getCurrent().setErrorHandler(new DefaultErrorHandler() {
            @Override
            public void error(com.vaadin.server.ErrorEvent event) {
                // Find the final cause
               
CustomExceptionHandler .getInstance().writeException(event.getThrowable());
                ExceptionWriter exceptionWriter = ExceptionWriter.getCurrentInstance();
                String cause = "
The server is unable to respond at this time. Thank you for your patience.<br>"
                        + "
An unexpected error occurred, please contact System Administrator with the following number :"
                        +  exceptionWriter.getExceptionID();
              
                // Display the error message in a custom fashion
                CustomLayout content = new CustomLayout("ErrorPage");
                VerticalLayout container = new VerticalLayout();
                container.addComponent(new Label(cause, ContentMode.HTML));
                content.addComponent(container, "errorContent");
                // add link to home page
                // add link to home page
                Button toHomePage = new Button("Back to Home page");
                toHomePage.setStyleName("link");
                toHomePage.addClickListener(new Button.ClickListener() {
                    public void buttonClick(Button.ClickEvent event) {
                        Page.getCurrent().reload();
                    }
                });
                content.addComponent(toHomePage, "homepagelink");
                setContent(content);      

                // Do the default error handling (optional)
                doDefault(event);
              }
        });
    }


Please note, I dont have @PreserveOnRefresh, so when I do a reload() from the above method it automatically calls init() again and continue the web app normally.

So, when everything is up and running you see something like this :
(it's in Dutch, but you get it :) ).

 

Notice the number at the end of the second line. Lets check the file then :

 

And the content will look like :

 

Different technologies involved in this :

Vaadin 7.6
Weblogic Server 10.3.6
Java 1.6

Happy coding.

Comments

Popular posts from this blog

Rich Text Editor - Oracle JET

Oracle JET has a lot of excellent UI components, but according to Murphy's law, client always comes up with something which you don't have at your disposal. So, driven by one of my client's requirements, I created a Rich Text Editor or WYSIWYG editor for Oracle JET. This is based on Quill JS and fully customizable. Github project download: https://github.com/sohamda/JET-Web-Components/tree/master/rich-text-editor I will explain in this blog, on how to integrate it in your own Oracle JET project. 1. Create and initialize your JET application and then put the downloaded web component inside "src\js\jet-composites" folder. 2. Once copied update your viewModel first. Add a snippet for passing the default content to be displayed by the editor after load. 3. Update view to load this editor Above you can see the "toolbar-options" property, that controls which options you should display to user on the editor. Those are basically the forma

Create Micro CRUD services for Oracle Database Cloud using NodeJS

I will try to explain, how you can use NodeJS to create mirco services for the tables in your Oracle Database Cloud or on-premise Database. Complete Github project : https://github.com/sohamda/LeasifyAPIs You need to do "npm install" to download the node_modules. Step by Step guide : 1. NodeJS : either 32 or 64 bit. If you already have NodeJS installed, please check whether it is 64 or 32. Use below command to figure that out : C:\>node > require('os').arch() If you get : 'ia32' , then it is 32 bit installation. 2. Install oracle-db node module .  This was a lengthy and time consuming installation for me, because for Windows, it has a lot of pre-requisites. If you are a Mac user, you are lucky. :) I followed : https://community.oracle.com/docs/DOC-931127 There is also a detailed one in github : https://github.com/oracle/node-oracledb/blob/master/INSTALL.md 3. Config your DB Cloud Create a user and couple of tables on which we'

Layout Management & CSS Classes with Oracle JET

Oracle JET provides automatic responsive layout using CSS classes. So that, from large screens to small screens the application fits itself the best possible way. JET’s layout management are based on 2 types of CSS classes “Responsive Grid” and “Flex”. Responsive grid classes which deals with size, number of columns and functions of a particular <div>. Naming convention of these classes are oj- size - function - columns sizes can be: sm, md, lg, xl functions can be: hide, only-hide columns can be: any number between 1 to 12.   Just like Bootstrap, JET also divides the width of the available space into 12 columns, so for example, if you want a section of your page should take up atleast 5 columns if you divide the available screen into 12 columns, you need use : oj- size -5. Now comes the size part, you need to define that for each size of the screen, from hand-held mobile devices to large or extra large desktop screens. With combination with theses grid c