C# best practice error handling and passing error messages

后端 未结 4 551
独厮守ぢ
独厮守ぢ 2021-01-15 02:28

I am using asp.net and I am always struggling for a neat way to handle errors and if there are any, to pass the errormessage to the user. For example, I have an User class,

4条回答
  •  醉酒成梦
    2021-01-15 03:09

    I think you missed the right way to do exception handling. Storing the text that is language/locale dependent in your database is not really a good idea. The error might also not be meaningful in the context in which it it executed, the caller of the method knows what is intended but the code that retrieves a value from a database does not know about the "higher goals" of your code! The description of the database error might also not interest users at all, for them the system just cannot get the list of users, that's all. For developers it is important to know what exactly got wrong. Putting this visible to users might also show them data you do not want them to see like table names, passwords, database user names, depending on what the exception contains (which you cannot control)

    So now how to handle it:

    1. Catch the exception where you handle it, that is in the onClick_Event
    2. Log out to a file detailed info, to the page only what users should see
    3. In your code (Database for e.g.) follow this principle:

      • Do not modify the object's state until it's clear that nothing can go wrong to keep your object in a consistent state. That means do not start to modify members, then the exception comes and you would have to reset them all to their previous state in a finally block.
      • Start your operations and throw an exception on problems (do not catch it here, pointless, you would just store a message or the whole exception for later retrieval!)
      • On success, copy the temporary variables to the members of the object

    This way you would always have an object in a consistent state and clean code.

提交回复
热议问题