C#: Throwing Custom Exception Best Practices

前端 未结 8 947
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 01:25

I have read a few of the other questions regarding C# Exception Handling Practices but none seem to ask what I am looking for.

If I implement my own custom Exception

8条回答
  •  攒了一身酷
    2020-11-30 02:23

    I always add a couple of properties when creating a custom exception. One is user name or ID. I add a DisplayMessage property to carry text to be displayed to the user. Then, I use the Message property to convey technical details to be recorded in the log.

    I catch every error in the Data Access Layer at a level where I can still capture the name of the stored procedure and the values of the parameters passed. Or the inline SQL. Maybe the database name or partial connection string (no credentials, please). Those may go in Message or in their own new custom DatabaseInfo property.

    For web pages, I use the same custom exception. I'll put in the Message property the form information -- what the user had entered into every data entry control on the web page, the ID of the item being edited (customer, product, employee, whatever), and the action the user was taking when the exception occurred.

    So, my strategy as per your question is: only catch when I can do something about the exception. And quite often, all I can do is log the details. So, I only catch at the point where those details are available, and then rethrow to let the exception bubble up to the UI. And I retain the original exception in my custom exception.

提交回复
热议问题