package org.apache.struts.action;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.config.ExceptionConfig;
import org.apache.struts.util.ModuleException;

public class ExceptionHandler {
  public ActionForward execute(Exception ex, ExceptionConfig ae, ActionMapping mapping, ActionForm formInstance, HttpServletRequest request, HttpServletResponse response) throws ServletException {
    ActionForward forward = null;
    ActionError error = null;
    String property = null;
    if (ae.getPath() != null) {
      forward = new ActionForward(ae.getPath());
    } else {
      forward = mapping.getInputForward();
    } 
    if (ex instanceof ModuleException) {
      error = ((ModuleException)ex).getError();
      property = ((ModuleException)ex).getProperty();
    } else {
      error = new ActionError(ae.getKey(), ex.getMessage());
      property = error.getKey();
    } 
    request.setAttribute("org.apache.struts.action.EXCEPTION", ex);
    storeException(request, property, error, forward, ae.getScope());
    return forward;
  }
  
  protected void storeException(HttpServletRequest request, String property, ActionError error, ActionForward forward, String scope) {
    ActionErrors errors = new ActionErrors();
    errors.add(property, error);
    if ("request".equals(scope)) {
      request.setAttribute("org.apache.struts.action.ERROR", errors);
    } else {
      request.getSession().setAttribute("org.apache.struts.action.ERROR", errors);
    } 
  }
}
