简体   繁体   中英

How do you handle/log errors in a Java MVC web application?

I'm currently using a very simple MVC framework, Bear Bibeault's Front Man , which, for those not familiar, is pretty similar to Spring MVC (in concept at least). One of the issues I'm having is how to handle exceptions properly.

I am currently doing something like this,

try {
    //do something
}catch (Exception ex) {
    logger.error("Logging error", ex);
    Map model = new HashMap();
    model.put("error", ex.getLocalizedMessage());
    cc.setScopedVariable("model", model);
    cc.forwardToView(ERROR_VIEW);
}

Essentially I log the exception and then forward to an error view page.

However this strikes me as not being the right way to do this. It results in a lot of boilerplate code that isn't very DRY.

What is a better way to handle/log exceptions in a web application?

You could do all of your logging inside an error JSP file .

Add this to your web.xml file.

<error-page> 
<exception-type>java.lang.Throwable</exception-type> 
<location>/error.jsp</location> 
</error-page>

In your jsp file add

<%@page isErrorPage="true" %>

Then you can place your logging inside <% %> and display the error at the same time. All of your logging logic would be in one place and your code would begin to look cleaner.


Instead of using a scriptlet in your JSP file, you could have the location point to a servlet. The servlet could handle all of your processing then forward to the JSP page.

You can also use this technique for different exceptions, so you could process the exceptions differently.

There are varying kinds of exceptions so you should first identify how you want to show them to the user. Forwarding them to a page to display an error may not be the best choice for all of the errors they encounter also keep in mind displaying an error without context can be confusing to some end users.

One way you could handle it would be log all of the none critical errors and have a location on the website where a user could access and review them. (I worked on a project where we had something similar to this. The user could review warnings and errors that wouldn't prevent the application from proceeding.)

You could return them to the page in which the error occurred and populate an error message there. AJAX/Comet could be used to display real time errors to the user without taking them away from the page where the error occurred.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM