Let's say you've got a Spring web app with a开发者_运维技巧 structure like this:
com/
myapp/
controller/
model/
service/
How should you handle exceptions that occur below the level of the controller?
Should you make methods in the Model and Service layers throw their exceptions up to the Controller layer?
What to do with them once they reach the Controller?
Do you always show the same error page to users but write a detailed exception to the log files?
It very much depends on the concrete case:
you can show the exception message (translated by some exception translation mechanism to a human-readable representation) together with validation message - for example "Email sending failed, please try again later"
If the exception can't be recovered from, you can redirect to a page which will display human-readable explanation
you can redirect to a generic 500 page that says "Oops, something went wrong"
Pick one option that you feel best fits your use-case in terms of usability.
I think logging and handling system exceptions should be done by the service layer. If you think about it in service-oriented terms, there may not be a UI calling a particular service. All system level cleanup needs to happen in that layer.
With that said, no exception should ever escape the controller layer. There needs to be enough communication between the service and controller layers so the controller can tell the user what's going on in friendly, easy-to-understand terms. Communicating back to users is the controller's duty.
精彩评论