I didn’t know it was this easy to handle Exceptions in .Net Core Web API. EasyException !!

An exception is a problem that arises during the execution of a program. A C# exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero.

Exceptions provide a way to transfer control from one part of a program to another. C# exception handling is built upon four keywords: trycatchfinally, and throw.

Now that we have come to an era on Middlewares we now use a middle to handle all kinds of Exception at one place.

This is where EasyExceptions comes in. Click here

This Lightweight Library removes your headache of defining a error response standard and just let you think about handling exceptions and what error code to be returned.

The library Implements the standard model suggested by Microsoft to handle errors/faults in system and correclty respond to it.

The Library lets you implement all the logics you want when an exception takes place in your system, and then later converts the ErrorResponse to client/users .

How to Use the Library?

Using the library is really simple.

You might have different exception in you system.

Say a domain Exception,

public class ProfileDomainException : Exception
{
   public ProfileDomainException(string message) : base(message)
   {
   }
}

and just like this many more.

So you Implement an interface Exposed by the EasyExtention library IErrorHandlingService as below\

you can Implement the above Interface like the below sample.

using EasyException.Abstractions;

 public class ErrorHandlingService : IErrorHandlingService
    {
        public Task<ErrorResponse> HandleException(Exception exception)
        {
            switch (exception)
            {
                case ProfileApiException ex:
                    return Task.FromResult<ErrorResponse>(new ErrorResponse() { Code = "ApiError", Message = exception.Message });

                case ProfileDomainException ex:
                    return Task.FromResult<ErrorResponse>(new ErrorResponse() { Code = "DomainError", Message = exception.Message });

                case ProfileApplicationException ex:
                    return Task.FromResult<ErrorResponse>(new ErrorResponse() { Code = "AppError", Message = exception.Message });

                default:
                    return Task.FromResult<ErrorResponse>(new ErrorResponse() { Code = "InternalError", Message = exception.Message });
            }
        }
    }

Now , in the StartUp.cs you can then register your Implementation as a singleton

 public void ConfigureServices(IServiceCollection services)
 {
  services.AddSingleton<IErrorHandlingService,ErrorHandlingService>();
  ...
  

And then configuring the app builder you can tell the app to use the middleware.

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
 {
   app.UseEasyExceptionHandling();
   ...
   

Now we can see the response can be in the below format .

ErrorResponse : Object
PropertyTypeRequiredDescription
errorErrorThe error object.
Error : Object
PropertyTypeRequiredDescription
codeStringOne of a server-defined set of error codes.
messageStringA human-readable representation of the error.
targetStringThe target of the error.
detailsError[]An array of details about specific errors that led to this reported error.
innererrorInnerErrorAn object containing more specific information than the current object about the error.
InnerError : Object
PropertyTypeRequiredDescription
codeStringA more specific error code than was provided by the containing error.
innererrorInnerErrorAn object containing more specific information than the current object about the error.
{
    "code": "BadArgument",
    "message": "Previous passwords may not be reused",
    "target": "password",
    "innererror": {
      "code": "PasswordError",
      "innererror": {
        "code": "PasswordDoesNotMeetPolicy",
        "minLength": "6",
        "maxLength": "64",
        "characterTypes": ["lowerCase","upperCase","number","symbol"],
        "minDistinctCharacterTypes": "2",
        "innererror": {
          "code": "PasswordReuseNotAllowed"
        }
      }
    }
  }

ITs Done !! Its that easy. All you logic of handling the exceptions are now in one place.

Thanks

Happy Coding!