java中自定义异常拦截器

来源:互联网 发布:网络集成实施方案 编辑:程序博客网 时间:2024/06/16 16:11

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
*
* 描述:异常的拦截器

*/

public class ExceptionInterceptor extends AbstractInterceptor{

private Log log = LogFactory.getLog(getClass());

public String intercept(ActionInvocation invocation) throws Exception {
try {
return invocation.invoke();  //放行
} catch (AppException e) {  //自定义异常
//记录错误日志

ActionSupport as = (ActionSupport) invocation.getAction();
as.addActionError(as.getText(e.getMessage())); //获取异常信息
e.printStackTrace();
log.error(e);
return "error";
} catch (Exception e) {
//记录错误日志

ActionSupport as = (ActionSupport) invocation.getAction();
as.addActionError("对不起,服务器已关闭,请联系管理员!");
e.printStackTrace();
log.error(e);
return "error";
}
}

}


Struts配置中

 <package name="" namespace="" extends="">
   
<interceptors>   
   
<interceptor name="exceptionInterceptor" class="ExceptionInterceptor类的全类名"/>   
   
<interceptor-stack name="
myStack">
    <interceptor-ref name="exceptionInterceptor"/> 
    <interceptor-ref name="defaultStack"/>
    </interceptor-stack>
    </interceptors>
   
    <default-interceptor-ref name="
myStack"/>

</package>


自定义异常

public class AppException extendsRuntimeException{ }


0 0
原创粉丝点击