---
title: "Struts1.X个性化异常学习"
author: "wikimo"
date: "2009-01-29T15:43:53Z"
tags: []
slug: "struts1-x"
draft: false
lastmod: "2010-01-01T11:27:03Z"
id: 320878
url: "https://wikimo.iteye.com/blog/320878"
---

1.编写自己的个性化异常类。该类中，可以包含成员变量errorCode.需要填充properties占位符的args数组的Object数组类型成员变量。并定义他们的get()方法。定义四个构造函数，第一个构造函数为空，第二个构造函数为带errorCode,Object数组的构造方法，第三个为带errorCode参数的构造方法，第四为带errorCode参数，一个Object类型参数（非数组）的构造方法。后两个构造方法的实现中可以直接调用第二个声明个构造方法。

 

ErrorCodeException类：

```
package wiki.struts;  
public class ErrorCodeException extends RuntimeException {
	
	//define the error code,
	//it is related to the properties file.
	private String errorCode;
	
	//if you want to dynamic fill with the args,use it object array.
	private Object[] args;
	
	public ErrorCodeException(){}
	
	//if not need to fill with the args in the properties.
	public ErrorCodeException(String errorCode){
		this(errorCode,null);
	}
	
	//if you want to fill with the args in the properties.
	public ErrorCodeException(String errorCode,Object args0){
		this(errorCode,new Object[]{args0});
	}
	
	
	public ErrorCodeException(String errorCode,Object[] args){
		this.errorCode = errorCode;
		this.args = args;
	}
	
	public String getErrorCode() {
		return errorCode;
	}
	
	public Object[] getArgs() {
		return args;
	}
}
  
```

 

2.编写相应的ExceptionHandler类，继承自原有的ExceptionHandler。重写execute()方法。

 

ErrorCodeExceptionHandler类：

package wiki.struts; 

import javax.servlet.ServletException;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import org.apache.struts.Globals;  
import org.apache.struts.action.ActionForm;  
import org.apache.struts.action.ActionForward;  
import org.apache.struts.action.ActionMapping;  
import org.apache.struts.action.ActionMessage;  
import org.apache.struts.action.ExceptionHandler;  
import org.apache.struts.config.ExceptionConfig;  
import org.apache.struts.util.ModuleException;

public class ErrorCodeExceptionHandler extends ExceptionHandler {  
     
    public ActionForward execute(  
            Exception ex,  
            ExceptionConfig ae,  
            ActionMapping mapping,  
            ActionForm formInstance,  
            HttpServletRequest request,  
            HttpServletResponse response)  
            throws ServletException {

            **if(!(ex instanceof ErrorCodeException)){**  
                **return super.execute(ex, ae, mapping, formInstance, request, response);**  
            **}**  
             
            ActionForward forward = null;  
            ActionMessage error = null;  
            String property = null;

            // Build the forward from the exception mapping if it exists  
            // or from the form input  
            if (ae.getPath() != null) {  
                forward = new ActionForward(ae.getPath());  
            } else {  
                forward = mapping.getInputForward();  
            }

            // Figure out the error  
            if (ex instanceof ModuleException) {  
                error = ((ModuleException) ex).getActionMessage();  
                property = ((ModuleException) ex).getProperty();  
            } else {  
                //deal with the exception,if the instance of  
                //exception is ErrorCodeException.  
                **ErrorCodeException ece = (ErrorCodeException)ex;**  
                **error = new ActionMessage(ece.getErrorCode(), ece.getArgs());**  
                **property = error.getKey();**  
            }

            this.logException(ex);

            // Store the exception  
            request.setAttribute(Globals.EXCEPTION\_KEY, ex);  
            this.storeException(request, property, error, forward, ae.getScope());

            return forward;  
        }  
}

3.配置struts-config.xml&lt;exception/&gt;中的key值可以任意指定，type为自己的个性化异常类，handler为在2中编写的ExceptionHandler类。

```
<exception key="error.exception"
			type="wiki.struts.ErrorCodeException"
			handler="wiki.struts.ErrorCodeExceptionHandler"


			path="/login_error.jsp"
			/>
```