ilya.stmn
ilya.stmn

Reputation: 1624

RuntimeException handling in java web application

I've faced an interesting aim, this aim targets the exception handling in existing web application written with wicket and hibernate frameworks, suppose we have web app which is deployed in server and sometimes it produces runtime exceptions, the problem is how to get and save their stacktrace to db without modifying all classes(about 80 models and 150 views).

Hope i gave all clear.
Thanks in advance.

Upvotes: 1

Views: 1867

Answers (3)

Xavi López
Xavi López

Reputation: 27880

Wicket 1.4 and earlier

Override Application.newRequestCycle() and return a custom subclass of WebRequestCycle that overrides RequestCycle.logRuntimeException() in order to provide additional logging behavior for all RuntimeExceptions in your application. Notice that any uncaught Exception will be wrapped by Wicket in a WicketRuntimeException (as stated in the Exception handling section of Request cycle and request cycle processor) :

There, use a Service/DAO component that will insert the exception message along with the stacktrace into the database. Remember that depending on the dbms, you might want to use a CLOB instead of a varchar type (for instance, in Oracle, a varchar column cannot hold more than 4000 bytes).

Here's an (untested) example:

public class myApplication extends WebApplication { 
    ...
    @Override
    public RequestCycle newRequestCycle(Request request, Response response) {
        return new myRequestCycle(this, (WebRequest) request, (WebResponse) response);
    }
} 

public class myRequestCycle extends WebRequestCycle { 
    ...
    @Override
    protected void logRuntimeException(RuntimeException rex) {
        super.logRuntimeException(rex);
        Writer w = new StringWriter();
        t.printStackTrace(new PrintWriter(w));
        String stackTrace = w.toString();
        someService.logExceptionToDB(rex.getMessage(),stackTrace);
    } 
} 

Wicket 1.5 and later

See @Cristoph's answer

Upvotes: 5

Christoph Leiter
Christoph Leiter

Reputation: 9345

You can use an IRequestCycleListener to log/handle your exceptions:

public class MyExceptionReporter extends AbstractRequestCycleListener {

    @Override
    public IRequestHandler onException(RequestCycle cycle, Exception ex) {
        // log exception here
        return null;
        // if you want to also show an error page:
        // return new RenderPageRequestHandler(new PageProvider(new ExceptionPage(ex)));
    }
}

Then register it in WebApplication#init:

getRequestCycleListeners().add(new MyExceptionReporter());

Upvotes: 6

Chris
Chris

Reputation: 5654

Write a utility which uses StackTraceElement[] to give you the complete stacktrace. Use an implementation of OutputStream to push it to a CLOB object. (I don't think BLOB is needed)

Upvotes: 0

Related Questions