java中处理异常的可管理方法
我正在尝试想出一种可管理的方法来处理 DAO 中的异常。通常,我的 DAO 中的方法如下所示:
public ArrayList fetchColors (String id)
{
//call iBatis SqlMapClient
//put results in a list
//return list
}
如果上述代码中发生错误,则所有内容都会写入 server.log
,并在首页上显示自定义错误屏幕。但是,我想避免将堆栈跟踪放入 server.log 中,而是将其写入 my_app.log
(我正在使用 log4j)。
所以我计划将上述方法转换为以下方法:
public ArrayList fetchColors (String id) throws SqlException
{
try {
//call iBatis SqlMapClient
//put results in a list
}
catch (SqlException e)
{
logger.log (e);
throws e;
}
//return list
}
问题
- 这是解决问题的最佳方法吗?
- 我在 DAO 中有很多方法,对每个方法执行上述操作将是一个 PITA。是否有更简单的方法来执行此操作,以便同样的事情适用于 DAO 中的所有方法?
I am trying to come up with a manageable way to handle exceptions in a DAO. Typically a method in my DAO looks like this:
public ArrayList fetchColors (String id)
{
//call iBatis SqlMapClient
//put results in a list
//return list
}
If an error happens in the above code then everything is written to server.log
and on the front page I show custom error screen. However, I want to avoid to put the stacktrace to server.log but instead write it to my_app.log
(I'm using log4j).
So I'm planning to transform above method to following:
public ArrayList fetchColors (String id) throws SqlException
{
try {
//call iBatis SqlMapClient
//put results in a list
}
catch (SqlException e)
{
logger.log (e);
throws e;
}
//return list
}
Questions:
- Is this the best way to approach the problem?
- I have lot of methods in the DAO and doing the above for each method will be a PITA..Is there an easier way to do this so same thing applies to all the methods in a DAO?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为你可以在这里使用AOP。例如:
另外,作为旁注,您应该始终像这样记录,以便您可以在日志文件中看到堆栈跟踪。
I think you can use AOP here. For example:
Also as a side note you should always log like this so that you can see the stack trace in the log file.
一种“回调”解决方案,用于处理异常并在一个地方登录:
定义一个框架方法,如下所示:
调用它:
A 'callback' solution in order to handle exception and log in one place:
Define a skeleton method like:
Call it like:
我建议您添加一些使用 Spring AOP 进行日志记录。正如 CoolBeans 所示,您可以简单地使用 @AfterThrowing 建议。
I recommend you add some method logging with Spring AOP. As CoolBeans showed, you can simply use an @AfterThrowing advice.