Replacing an exception using Replace handler

Replacing an exception is one of the common requirements to avoid exposing more than the required information especially while dealing with sensitive information. Imagine a scenario where a component throws the original exception, which might contain sensitive information such as connection string, stack trace, and so on, to the consumer. The Exception Handling Application Block provides the Replace handler to replace the exception with a custom exception and message.

Configuring a Replace handler

Let us update the existing configuration file with a Replace handler. In this scenario, we will replace a DbException with an ApplicationException and set a custom message. This prevents the Data Access Layer from exposing sensitive information such as connection string and so on.

  1. Add a new policy in the policies section and name it Data Access Layer Policy as shown in the following screenshot:
    Configuring a Replace handler
  2. Right-click on the Data Access Layer Policy and click on Add Exception Type; this will pop up a new exception type selection dialog.
    Configuring a Replace handler
  3. Specify the type name as DbException by keying in the type name.
    Configuring a Replace handler
  4. Set the Post handling action attribute of the exception type DbException to ThrowNewException.
    Configuring a Replace handler
  5. So far we have added the policy and the exception type. Now let's add the Replace exception handler. Right-click on the exception type DbException and click on Add Handlers | Add Replace Handler.
    Configuring a Replace handler
  6. Set the exception message and also set the replace exception type to System.ApplicationException.
    Configuring a Replace handler

So far we have successfully configured the application with a policy that will process an exception of type DbException or any matching exception in the class hierarchy. It also replaces the exception with a new System.ApplicationException with the specified exception message; a new exception is thrown as configured in the post-handling action.

The following is the execution result of Exception Replace Demo provided as part of the sample application with this book:

Exception Message:
===================
Replaced Exception: Application exception occured. Error code: 6a45a1e8-e131-421d-a1f4-7a73cdb16198

As we can see in the above result, the original DbException has been replaced with ApplicationException. Additionally, the message also provides a unique error code to trace the root of the exception. This helps in protecting sensitive data from being exposed to other layers or users.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.146.37.250