web api and external dll call exception handling

Spunny 326 Reputation points
2023-07-25T14:17:51.7633333+00:00

Hi All,

I have an .net framework 4.8 web api in C#. The web api end point fires a process (which is in another dll) which is a long process using Task.Run. The web api end point is used to just fire and forget about process. All business logic takes place in that dll that is referenced in web api project.

I need to add exception handling to all these. All dlls references for process to run are our own projects. Since this web api is for fire and forget style end point, where should I implement exception handling (business dll project or data access project dll ) or catch exception and throw to web api and handle there. When exception occurs, we don't have user interface to show to user. So, we would like to write to text file and send details in an email.

Your suggestions are appreciated. If you can provide code or links, that would be great.

Thank You

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,648 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Jiale Xue - MSFT 43,046 Reputation points Microsoft Vendor
    2023-07-27T08:45:11.8066667+00:00

    Hi @Spunny ,

    The web api end point fires a process (which is in another dll) which is a long process using Task.Run. The web api end point is used to just fire and forget about process.

    You can tell from your description.

    Web Api is only used to start the process, why should errors be handled in web Api?

    Just put your error handling in the corresponding DLL.

    Here are the advantages of putting error handling in the DLL:

    Single Responsibility Principle: Let the DLL handle exceptions by itself in line with the Single Responsibility Principle, that is, each component is responsible for its own task. The business DLL knows how to handle its exceptions, and the Web API layer does not need too much exception handling logic.

    Code reuse: If you have other projects or applications that also use this business DLL, they will automatically inherit the same error handling logic without having to implement it repeatedly.

    Encapsulation Details: A DLL is a separate unit that encapsulates business logic. Hiding the exception handling logic inside the DLL can prevent the Web API layer from relying too much on business details.

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments