strutsグローバルエラー処理ページの構成
9982 ワード
まずstrutsファイルには次のように構成されています.
package name="default"extends="struts-default">
class="com.aicaipiao.admin.interceptor.ExceptionInterceptor"/>
/index.jsp
/login.jsp
/public/error.jsp
/public/message.jsp
result="failure"/>
result="failure"/>
次にjavaクラスです.
次に、カスタム例外処理クラスを指定します.
カスタム例外コードクラス:
package name="default"extends="struts-default">
次に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;
}
}