用struts2的ExceptionMappingInterceptor
[code="java"]
package com.erry.core.web.interceptor;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.springframework.dao.DataAccessException;
import com.erry.exception.BusinessException;
import com.erry.exception.DaExceptionTranslator;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.ExceptionHolder;
import com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor;
import com.opensymphony.xwork2.util.LocalizedTextUtil;
public class ExceptionInterceptor extends ExceptionMappingInterceptor {
/**
*
*/
private static final long serialVersionUID = -108722874114862093L;
private DaExceptionTranslator daExTranslator = new DaExceptionTranslator();
private boolean debug = false;
protected void publishException(ActionInvocation invocation, ExceptionHolder exceptionHolder) {
String detailedInfo;
List<String> errMessage = new ArrayList<String>();
// try {
detailedInfo = exceptionHolder.getExceptionStack();
// } catch (IOException e) {
// detailedInfo = "";
// }
if (exceptionHolder.getException() instanceof BusinessException) {
errMessage = getBusiExceptionMessage(invocation, (BusinessException) exceptionHolder.getException());
} else if (exceptionHolder.getException() instanceof DataAccessException) {
BusinessException e = daExTranslator.tranlate((DataAccessException) exceptionHolder.getException());
errMessage.addAll(getBusiExceptionMessage(invocation, e));
} else {
errMessage.add(getMessage(invocation, "unknown_error", null));
}
invocation.getStack().set("detailedInfo", detailedInfo);
invocation.getStack().set("errMessage", errMessage);
if (debug) {
exceptionHolder.getException().printStackTrace();
}
}
private List<String> getBusiExceptionMessage(ActionInvocation invocation, BusinessException e) {
List<String> errors = new ArrayList<String>();
BusinessException be = e;
while (be != null) {
String msgKey = "bussiness_exception_" + be.getErrorCode();
errors.add(getMessage(invocation, msgKey, be.getArgs()));
be = be.getLinkedException();
}
return errors;
}
private String getMessage(ActionInvocation invocation, String msgKey, Object[] args) {
Locale locale = invocation.getInvocationContext().getLocale();
return LocalizedTextUtil.findText(invocation.getAction().getClass(), msgKey, locale, msgKey, args);
}
public boolean isDebug() {
return debug;
}
public void setDebug(boolean debug) {
this.debug = debug;
}
}
[/code]