如果应用程序没有捕获到异常,则Struts2会将异常抛到前端,并不会在后台输出日志,这个给程序调式跟踪带来不便,因此要对异常进行统一处理。
1.异常处理action类:
public class ExceptionProcessorAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private static final Logger log = Logger.getLogger(ExceptionProcessorAction.class.getName());
private Exception exception;
public String execute() {
if (exception != null) {
log.log(Level.SEVERE, "服务器内部错误", exception); // 输出到后台
WriterUtil.write(AjaxResult.error().setMsg(exception.getMessage()));
}
return null;
}
public Exception getException() {
return exception;
}
public void setException(Exception exception) {
this.exception = exception;
}
}
2.在struts.xml中进行以下配置:
<global-results>
<result name="error" type="chain">
<param name="actionName">exceptionProcessor</param>
</result>
</global-results>
<global-exception-mappings>
<exception-mapping result="error" exception="java.lang.Exception"></exception-mapping>
</global-exception-mappings>
<!-- 统一异常处理action -->
<action name="exceptionProcessor" class="com.xxx.common.ExceptionProcessorAction" />
|