no.dusken.common.spring.ExceptionHandler.java Source code

Java tutorial

Introduction

Here is the source code for no.dusken.common.spring.ExceptionHandler.java

Source

/*
 Copyright 2006 - 2010 Under Dusken
    
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
    
 http://www.apache.org/licenses/LICENSE-2.0
    
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
package no.dusken.common.spring;

import no.dusken.common.model.Mail;
import no.dusken.common.util.MailSender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author Marvin B. Lillehaug<lillehau@underdusken.no>
 */
public class ExceptionHandler extends SimpleMappingExceptionResolver {

    private MailSender mailSender;
    /**
     * The address exceptionmails are sent from.
     */
    private String mailAddress;
    /**
     * A list of Exceptions that we do not send mail about.
     */
    private Properties ignoreExceptions;
    /**
     * The address mail is sent from.
     */
    private String fromAddress;
    /**
     * The name of the sender.
     */
    private String fromName;
    /**
     * The template used for generating the mail.
     */
    private String exceptionMailTemplate;

    /**
     * If false, mail will no be sent when a exception accurs.
     */
    private boolean sendMail;

    private static final Logger log = LoggerFactory.getLogger(ExceptionHandler.class);

    /**
     * sends mail to mailAddress with the exception if the exceptions isn't in the ignoreExcptions
     * @return super.doResolveException
     */
    @Override
    protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response,
            Object handler, Exception ex) {
        log.error("Exception thrown", ex);
        if (!ignoreExceptions.containsKey(ex.getClass().getCanonicalName()) && sendMail) {
            try {
                Mail mail = new Mail();
                mail.setFromAddress(fromAddress);
                mail.setFromName(fromName);
                mail.setToAddress(mailAddress);
                mail.setSubject(ex.toString());
                String body = getBody(request, ex);
                mail.setBody(body);
                Map map = new HashMap();
                map.put("exception", ex);
                mailSender.sendEmail(mail, map, exceptionMailTemplate);
            } catch (Exception e) {
                log.error("Sending of exceptionmail failed", e);
                //nevermind the exception, continue with the original exception
            }
        }
        response.setStatus(500);
        return super.doResolveException(request, response, handler, ex);
    }

    private String getBody(HttpServletRequest request, Exception ex) {
        StringBuilder builder = new StringBuilder();
        builder.append("Method: ");
        builder.append(request.getMethod());
        builder.append('\n');
        builder.append("Servletpath: ");
        builder.append(request.getServletPath());
        builder.append('\n');
        builder.append("URI: ");
        builder.append(request.getRequestURI());
        builder.append('\n');
        builder.append("Query: ");
        builder.append(request.getQueryString());
        builder.append('\n');
        builder.append("User-Agent: ");
        builder.append(request.getHeader("User-Agent"));
        builder.append('\n');
        builder.append("Accept: ");
        builder.append(request.getHeader("Accept"));
        builder.append('\n');
        builder.append("Accept-Encoding: ");
        builder.append(request.getHeader("Accept-Encoding"));
        builder.append('\n');

        builder.append("Stacktrace:");
        builder.append('\n');

        String stacktrace = getStackTraceAsString(ex.getStackTrace())
                + (ex.getMessage() == null ? "" : "| Message: " + ex.getMessage());
        builder.append(stacktrace);
        return builder.toString();
    }

    /**
     * @param mailAddress - the mailaddress exceptionmails should be sent to.
     */
    @Required
    public void setMailAddress(String mailAddress) {
        this.mailAddress = mailAddress;
    }

    /**
     * If a thrown exception is one of these properies, we do not send mail.
     * @param ignoreExceptions
     */
    @Required
    public void setIgnoreExceptions(Properties ignoreExceptions) {
        this.ignoreExceptions = ignoreExceptions;
    }

    private String getStackTraceAsString(StackTraceElement[] stackTrace) {
        StringBuffer string = new StringBuffer();
        for (StackTraceElement ste : stackTrace) {
            string.append(ste.toString()).append("\r\n");
        }
        return string.toString();
    }

    @Required
    public void setFromAddress(String fromAddress) {
        this.fromAddress = fromAddress;
    }

    @Required
    public void setFromName(String fromName) {
        this.fromName = fromName;
    }

    @Required
    public void setExceptionMailTemplate(String exceptionMailTemplate) {
        this.exceptionMailTemplate = exceptionMailTemplate;
    }

    @Required
    public void setSendMail(boolean sendMail) {
        this.sendMail = sendMail;
    }

    @Required
    public void setMailSender(MailSender mailSender) {
        this.mailSender = mailSender;
    }
}