---
title: "J2EE项目中的异常处理 这篇也写得不错 可惜不是我写的 "
author: "stta04"
date: "2009-04-09T12:44:00Z"
tags: []
slug: "j2ee"
draft: false
lastmod: "2009-04-09T12:44:00Z"
id: 377637
url: "https://stta04.iteye.com/blog/377637"
---

还有另一篇文章也写得非常好 同样不知道作者是谁

**1. checked 和 unchecked exceptions**  
致命错误， 不可恢复错误， 第三方包错误 包装为unchecked exception。  
业务逻辑异常流，安全异常包装为checked exception. J2ee应用中有Business exception,

DB exception, security exception, confirmation exception

**2. 抛出异常的策略**  
2.1 采用J2EE应用程序的 前端控制器（front controller) 集中控制处理，开发者实现具体的

业务逻辑的时候可以不关心异常的捕捉  
2.2 方法签名中throws 一个基类的异常。这样前端控制器中只要捕捉这个基类的异常，开发者

可以定义自己派生的异常具体类

**3. 在web层处理unchecked exceptions**  
所有的unchecked exceptions 都应该在web层进行处理， 可以在web.xml中配置异常发生时显

示定制的错误页面。

**4. 封装第三方包的所有异常（Exception)为一个我们定义的unchecked exception**

**5. 对来自数据库操作的checked exception**

比如Employee not found, Order not found可以抽

象一个RecordNotFoundException. 至于这个RecordNotFoundException是因为Employee还是Order

引起的作为context, 由context一起组成error code，抛给前端控制器。

**6. 前端控制器中的错误处理**  
基类的异常处理（应用模板方法设计模式 Template Method)和子类（实现业务）的部分代码如

下，以struts为例

public abstract class BaseAppDispatchAction  
extends DispatchAction{  
...  
protected static ThreadLocal  
expDisplayDetails = new ThreadLocal();

public ActionForward execute(  
ActionMapping mapping,  
ActionForm form,  
HttpServletRequest request,  
HttpServletResponse response) throws Exception{  
...  
try{  
String actionMethod = request  
.getParameter(mapping.getParameter());  
finalDestination =dispatchMethod(mapping,  
form, request, response,actionMethod);  
}catch (BaseAppException Ex) {  
ExceptionDisplayDTO expDTO =  
(ExceptionDisplayDTO)expDisplayDetails  
.get();  
IExceptionHandler expHandler =  
ExceptionHandlerFactory  
.getInstance().create();  
ExceptionDTO exDto = expHandler  
.handleException(  
expDTO.getContext(), userId, Ex);  
ActionErrors errors = new ActionErrors();  
errors.add(ActionErrors.GLOBAL\_ERROR,  
new ActionError(exDto  
.getMessageCode()));  
saveErrors(request, errors);  
return mapping.findForward(expDTO  
.getActionForwardName());  
} catch(Throwable ex){  
//log the throwable  
//throw ex;  
} finally {  
expDisplayDetails.set(null);  
}

业务子类中代码如下:  
...  
String exceptionActionForward =  
"SearchAdjustmentPage";  
String exceptionContext =  
"divisionAction.searchDivision";

ExceptionDisplayDTO expDTO =  
new ExceptionDisplayDTO(expActionForward,  
exceptionContext);  
expDisplayDetails.set(expDTO);  
...  
DivisionDTO divisionDTO =divisionBusinessDelegate  
.getDivisionByNum(fromDivisionNum);  
...

ExceptionDisplayDTO 作为data transfer object放在ThreadLocal中专门为了父类的异常处理

用

**7. Exception Handler**  
上面的集中异常控制是在Excepiton Handler中处理的,包括:  
根据异常类型获取异常代码,异常代码会用来显示异常信息. 异常类型与异常代码的对应关系

可以放到一个XML文件中. 根据异常代码取异常信息可以由ResouceBundle来实现,这样同时解决了

异常信息国际化的问题. 两个异常配置的xml文件如下:  
&lt;exception name="EmployeeConfirmationException"&gt;  
&lt;messagecode&gt;messagecode.employeeconfirmation&lt;/messagecode&gt;  
&lt;confirmationind&gt;true&lt;/confirmationind&gt;  
&lt;loggingtype&gt;nologging&lt;/loggingtype&gt;  
&lt;/exception&gt;  
&lt;exception name="RecordNotFoundException"&gt;  
&lt;messagecode&gt;messagecode.recordnotfound&lt;/messagecode&gt;  
&lt;confirmationind&gt;false&lt;/confirmationind&gt;  
&lt;contextind&gt;true&lt;/contextind&gt;  
&lt;loggingtype&gt;error&lt;/loggingtype&gt;  
&lt;/exception&gt;  
第二个异常文件考虑了我们上面讲的context问题. 如果抛出的异常是

RecordNotFoundException, 并且当前的context是order.getOrder , 那么error code就

是:messagecode.recordnotfound.order.getOrder

为了避免多次解析这个XML文件,可以实现一个ExceptionInfoCache ,启动应用时缓冲这个xml的内

容.

ExceptionHandler中handleException方法代码片断如下:

public ExceptionDTO handleException(String userId,  
BaseAppException exp) {  
ExceptionDTO exDTO = new ExceptionDTO();  
ExceptionInfoCache ecache =  
ExceptionInfoCache.getInstance();  
ExceptionInfo exInfo = ecache  
.getExceptionInfo(  
ExceptionHelper.getClassName(exp));  
String loggingType = null;  
if (exInfo != null) {  
loggingType = exInfo.getLoggingType();  
exDTO.setConfirmation(exInfo  
.isConfirmation());  
exDTO.setMessageCode(exInfo  
.getMessageCode());  
}

FileLogger logger = new FileLoggerFactory()  
.create();  
logger.logException(exp, loggingType);