webworm
webworm

Reputation: 11019

Handling exceptions from code in referenced projects

I have a C# console project where I have separated out the business logic from the UI. The business logic calls an API, retrieves JSON data, and then updates a database with the data. The UI handles the display of the results and also loops through a queue to process records with the business logic.

My question is how to properly handle exceptions thrown by the business logic. The UI project currently handles exceptions that bubble up but I want to give as detailed an error message as possible. For example, sometimes the API fails to authorize or may be down and I want to log that specific exception. The problem is the UI project does not know anything about HttpRequestException without me adding a reference to the System.Net.Http library, which creates a dependency I don't want.

What is the "best practice" for handling exceptions in a project other than where they are generated?

Upvotes: 0

Views: 58

Answers (2)

adv12
adv12

Reputation: 8551

If you want to pass detailed messages to the UI project without explicitly referencing System.Net.Http, consider catching these HTTP exceptions in the business logic, wrapping them in an exception type you define in that library, and re-throwing the new exception. Then your UI library only needs to know about the business logic library, which it's already referencing, and the business logic can provide the most informative message possible for things it can't properly recover from.

Upvotes: 1

John Saunders
John Saunders

Reputation: 161773

I'd say the best practice is to not handle them. You don't know what those exceptions are, so how can you "handle" them?

Either trust the Message property of these exceptions and display them to the users, or just tell the users "sorry, something bad happened".

Keep in mind that your users will need to read the detailed messages and decide what to do about them. Quite likely they'll either ignore the messages or else call someone to ask what to do about them. Make sure you log enough information to answer the call. Sometimes, you're just better off displaying a message that says, "Please call someone who can figure out what went wrong".

Upvotes: 0

Related Questions