`

struts配置全局的错误处理页面

 
阅读更多
首先struts文件里面配置如下:
package name="default" extends="struts-default">
<interceptors>
<interceptor name="exceptionInterceptor"
class="com.aicaipiao.admin.interceptor.ExceptionInterceptor" />
<interceptor-stack name="adminCompleteStack">
<interceptor-ref name="defaultStack" />
<interceptor-ref name="exceptionInterceptor" />
</interceptor-stack>
</interceptors>

<default-interceptor-ref name="adminCompleteStack" />
<global-results>
<result name="index">/index.jsp</result>
<result name="login">/login.jsp</result>
<result name="failure">/public/error.jsp</result>
<result name="message">/public/message.jsp</result>
</global-results>

<global-exception-mappings>
<exception-mapping exception="com.aicaipiao.common.service.exception.BusinessException"
result="failure" />
<exception-mapping exception="java.lang.Exception"
result="failure" />
</global-exception-mappings>
 
</package>


然后是java类:

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.*.admin.action.BaseAction;
import com.aicaipiao.common.service.exception.BusinessException;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.config.entities.ExceptionMappingConfig;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.opensymphony.xwork2.interceptor.ExceptionHolder;

public class ExceptionInterceptor extends AbstractInterceptor {

    private static final long serialVersionUID = 2888326289382964802L;

    private transient final Logger logger = LoggerFactory.getLogger(this.getClass());

    protected Logger categoryLogger;
    protected boolean logEnabled = false;
    protected String logCategory;
    protected String logLevel;

    public boolean isLogEnabled() {
        return logEnabled;
    }

    public void setLogEnabled(boolean logEnabled) {
        this.logEnabled = logEnabled;
    }

    public String getLogCategory() {
        return logCategory;
    }

    public void setLogCategory(String logCatgory) {
        this.logCategory = logCatgory;
    }

    public String getLogLevel() {
        return logLevel;
    }

    public void setLogLevel(String logLevel) {
        this.logLevel = logLevel;
    }

    @SuppressWarnings("rawtypes")
    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        String result;
        BaseAction action = (BaseAction) invocation.getAction(); //执行Action类
        try {
            result = invocation.invoke();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            if (e instanceof BusinessException) {

                action.addActionMessage(((BusinessException) e).getErrorCode().getMsg());
            } else {
                action.addActionMessage("系统错误,请联系系统管理员。");
            }
            List<ExceptionMappingConfig> exceptionMappings = invocation.getProxy().getConfig().getExceptionMappings();
            String mappedResult = this.findResultFromExceptions(exceptionMappings, e);
            if (mappedResult != null) {
                result = mappedResult;
                publishException(invocation, new ExceptionHolder(e));
            } else {
                throw e;
            }
        }

        return result;
    }

    /**
     * Handles the logging of the exception.
     * 
     * @param e  the exception to log.
     */
    protected void handleLogging(Exception e) {
        if (logCategory != null) {
            if (categoryLogger == null) {
                // init category logger
                categoryLogger = LoggerFactory.getLogger(logCategory);
            }
            doLog(categoryLogger, e);
        } else {
            doLog(logger, e);
        }
    }

    /**
     * Performs the actual logging.
     * 
     * @param logger  the provided logger to use.
     * @param e  the exception to log.
     */
    protected void doLog(Logger logger, Exception e) {
        if (logLevel == null) {
            logger.debug(e.getMessage(), e);
            return;
        }

        if ("trace".equalsIgnoreCase(logLevel)) {
            logger.trace(e.getMessage(), e);
        } else if ("debug".equalsIgnoreCase(logLevel)) {
            logger.debug(e.getMessage(), e);
        } else if ("info".equalsIgnoreCase(logLevel)) {
            logger.info(e.getMessage(), e);
        } else if ("warn".equalsIgnoreCase(logLevel)) {
            logger.warn(e.getMessage(), e);
        } else if ("error".equalsIgnoreCase(logLevel)) {
            logger.error(e.getMessage(), e);
        } else if ("fatal".equalsIgnoreCase(logLevel)) {
            logger.error(e.getMessage(), e);
        } else {
            throw new IllegalArgumentException("LogLevel [" + logLevel + "] is not supported");
        }
    }

    protected String findResultFromExceptions(List<ExceptionMappingConfig> exceptionMappings, Throwable t) {
        String result = null;

        // Check for specific exception mappings.
        if (exceptionMappings != null) {
            int deepest = Integer.MAX_VALUE;
            for (Object exceptionMapping : exceptionMappings) {
                ExceptionMappingConfig exceptionMappingConfig = (ExceptionMappingConfig) exceptionMapping;
                int depth = getDepth(exceptionMappingConfig.getExceptionClassName(), t);
                if (depth >= 0 && depth < deepest) {
                    deepest = depth;
                    result = exceptionMappingConfig.getResult();
                }
            }
        }

        return result;
    }

    /**
     * Return the depth to the superclass matching. 0 means ex matches exactly. Returns -1 if there's no match.
     * Otherwise, returns depth. Lowest depth wins.
     *
     * @param exceptionMapping  the mapping classname
     * @param t  the cause
     * @return the depth, if not found -1 is returned.
     */
    public int getDepth(String exceptionMapping, Throwable t) {
        return getDepth(exceptionMapping, t.getClass(), 0);
    }

    private int getDepth(String exceptionMapping, Class exceptionClass, int depth) {
        if (exceptionClass.getName().contains(exceptionMapping)) {
            // Found it!
            return depth;
        }
        // If we've gone as far as we can go and haven't found it...
        if (exceptionClass.equals(Throwable.class)) {
            return -1;
        }
        return getDepth(exceptionMapping, exceptionClass.getSuperclass(), depth + 1);
    }

    /**
     * Default implementation to handle ExceptionHolder publishing. Pushes given ExceptionHolder on the stack.
     * Subclasses may override this to customize publishing.
     *
     * @param invocation The invocation to publish Exception for.
     * @param exceptionHolder The exceptionHolder wrapping the Exception to publish.
     */
    protected void publishException(ActionInvocation invocation, ExceptionHolder exceptionHolder) {
        invocation.getStack().push(exceptionHolder);
    }
}


然后是自定义的异常处理类:



/**
 * 统一的业务异常超类
 *
 * Copyright (C) 2010-2012 www.2caipiao.com Inc. All rights reserved.
 */
public abstract class BusinessException extends RuntimeException {

    private static final long serialVersionUID = -7673793242894704838L;

    protected ErrorCode code;

    public BusinessException(String message) {
    	super(message);
        this.code = new ErrorCode(BetErrorTable.BUSINESS_COMMON_ERROR,message);
    }

    public BusinessException(ErrorCode code) {
        super(code.getMsg());
        this.code = code;
    }
    public BusinessException(ErrorCode code,Throwable cause) {
        super(code.getMsg(),cause);
        this.code = code;
    }

    /**
     * 根据一个异常编码来获取异常描述
     * @return
     * @create_time Nov 25, 2010 7:16:47 PM
     */
    public abstract ErrorCode getErrorCode();

}


自定义的异常码类:

import java.io.Serializable;

/**
 * 错误代码类
 * 
 * */
public class ErrorCode implements Serializable {

    private static final long serialVersionUID = -2892956957010575101L;

    /**错误代码**/
    public String code;

    /**错误代码对应消息**/
    public String msg;

    public String getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }

 
    public ErrorCode(String code, String msg) {
        this.msg = msg;
        this.code = code;
    }

}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics