Business Objects, Validation And Exceptions

后端 未结 18 883
自闭症患者
自闭症患者 2020-12-02 04:54

I’ve been reading a few questions and answers regarding exceptions and their use. Seems to be a strong opinion that exceptions should be raised only for exception, unhandled

18条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-02 05:22

    Assuming that you have separate validation and persist (i.e. save to database) code, I would do the following:

    1. The UI should perform validation. Don't throw exceptions here. You can alert the user to errors and prevent the record from being saved.

    2. Your database save code should throw invalid argument exceptions for bad data. It makes sense to do it here, since you cannot proceed with the database write at this point. Ideally this should never happen since the UI should prevent the user from saving, but you still need it to ensure database consistency. Also you might be calling this code from something other than the UI (e.g. batch updates) where there is no UI data validation.

提交回复
热议问题