2013年2月3日 星期日

Exception Handling (二)

承上篇

Exception Handling (一)


再看一個討論的例子,

Java: Error handling in MVC project. How correct implement?

How do you want to handle the error on DAO layer? Return fake data? Empty collection? if you can't, just let the exception pop-up.


And how about handling on the service layer? You know that the database is not working, so what can you return to the Struts action? An empty result? An error object? Isn't exception an error object?
So the exception appears in the Struts action. Here you have some options. If the exception will actually tell something to the user and your GUI is prepared, you can return different view (and log the exception here).
But what if you catch a NullPointerException in Struts action? Will you handle it separately in every Struts action? No, so pass the exception even further (!)
I think you get the idea - as long as you don't know how to handle the exception (and logging is not handling), let the client clean-up the mess. Otherwise you are only hiding the problem and increasing the damages (e.g. transactions aren't rolled-back, users see incorrect results).
I would advice implementing generic exception handling mechanism which logs the exception and returns HTTP 500 to the user. Gentle error message (without stack trace) should appear and the user should be apologized. You should investigate every error that reaches this layer.
As far as I remember Struts (and virtually every web framework) has some centralized way of handling exceptions. (Struts 2 Exception Handling Docs)


沒有留言:

張貼留言