异常处理
在实际项目开发中异常是需要统一 处理的,
截获OrgManagerImpl 中抛出的信息,要不要都行 |
利用struts 中的处理机制(1. 编程处理(手工):try/catch 截获异常(这种在 统一的时候不用) 2. 将异常抛出 交给struts 自动处理)
1. 手工 处理 ( 编程处理 )
在action 中
// 异常处理
try {
orgManager .delOrg(id);
} catch (Exception e) {
//1. 编程式处理 return mapping.findForward("del_fail");
//2. 手工处理
ActionMessages msgs= new ActionMessages();
ActionMessage msg=new ActionMessage(" errors.detail ",e.getMessage());
msgs.add( "detail " ,msg);
this.saveErrors(request, msgs);
return mapping.findForward( "exception" );
<forward name="exception" path="/org/exception.jsp"></forward>
2. Struts 中自动处理
Action
< action
path = "/org"
type = "org.springframework.web.struts.DelegatingActionProxy"
异常类型 |
MessageResources.properties 中定义的错误类型 |
name = "orgForm"
scope = "request"
parameter = "method"
>
<exception key="errors.detail" type="java.lang.RuntimeException" scope="request" path="/org/exception.jsp" ></exception> 这句就自动处理
< forward name = "index" path = "/org/index.jsp" ></ forward >
< forward name = "add_input" path = "/org/add_input.jsp" ></ forward >
</ action >
此种自动异常处理缺点:如果异常带很多参数,那么自动异常是没办 法处理多参数的
3. 不同异常用一个表示(两个不同异 常用一个异常框架处理)
定义统一的异常,通常通过构造器来 传递参数。
在 struts — config.xml 中将 exception 放在全局异常中
struts — config.xml
com.ygp.oa.manager 中创建 SystemException 类,继承 RuntimeException 类,并通过复写父类建立相关构造 器。
(此时 throw new SystemException(" 存在子机构,不允许删除 ","exception.org.del"); 可以在 MessageResources.properties 中定义相关异常)
默认情况下使用 struts 中异常处理器 handler,
< global-exceptions >
< exception key = "errors.detials"
type = "com.ygp.oa.manager.SystemException"
path = "/common/exception.jsp"
scope = "request"
handler = "com.ygp.oa.web.actions.SystemExceptionHandler"
>
</ exception >
</ global-exceptions >
package com.ygp.oa.web.actions; 中
public class SystemExceptionHandler extends ExceptionHandler {
public ActionForward execute(
Exception ex, // 后台传递过 来的 exception 通过 orgaction throw 抛出,传来exception
ExceptionConfig ae, // 代表exception 中的所有配置
ActionMapping mapping,
ActionForm formInstance,
HttpServletRequest request,
HttpServletResponse response)
throws ServletException {
return super .execute(ex, ae, mapping, formInstance, request, response);
}
}