Exception handling of controller and transaction control of service layer

Writing code recently involved some affairs. I finally straightened the code in the morning. I didn’t know where to do exception handling before, which caused the code to try-catch everywhere, which is quite ugly.

It is still based on the three layers of controller-service-dao to write code. Starting from the entry, the method of the controller layer corresponds to a certain url, which is aimed at application personnel, and should return information that they can understand, so the controller must do exception handling. Generally speaking, there will be a unified exception handling method;

the service layer is oriented to the controller, and some methods in the service layer must ensure its transactions, so it is quite necessary to perform transaction control in the service layer, and transaction control for multiple SQLs , if a certain sql fails to execute, then the executed sql statement should be rolled back; the

dao layer is more of a single sql statement, and there is no need for transaction control, because transaction overhead is not cheap (official original words);

based on the above Three points, let’s go back and think about exception handling. In general, exceptions should be thrown online and thrown all the way to the final processing layer. Therefore, there is no need to try-catch for the dao layer and service, and throw exceptions directly. can.

Correspondingly, it is the transaction configuration of spring. By default, spring only rolls back runtime exceptions. If the exception is handled at the dao layer, additional configuration is required, and spring will roll back the exception. Commonly used The configuration is @Transactional(rollbackFor=Exception.class)


Incidentally, a Java knowledge point is mentioned. Regarding the role of finally in try-catch-finally, finally was designed to close resources at the beginning. If you use the return statement in finally, it will be overwritten. The most common return value of try or catch is to override the exception. Even if the catch throws an exception, it will be overwritten and return the return value of the return statement in finally.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326879968&siteId=291194637