title: How to create custom Exception and Error handler in .Net Core?
body: <p>I develop a .NET Core 3 REST API using C#.</p>
  
  <p>I read a lot about this topic, and I implemented a custom exception handler middleware, which is work well. </p>
  
  <p>But I realized that the error messages are structured differently.</p>
  
  <p>For example, I use .Net Core Identity and when I try to save a username which is already saved, then I get an HTTP 400 with the following error response: (Sorry about that, I can't post images.)</p>
  
  <pre><code>error Array(1){
    0: {
      code: "...",
      description: ".."
    }
  }
  </code></pre>
  
  <p>And, I use too the Attribute validation, which gives this HTTPErrorResponse: </p>
  
  <pre><code>error: {
    .
    .
    .
    errors:{
      Password: Array(1) {
        0: "The field..."
      }
    }
  }
  </code></pre>
  
  <p>Finally, my custom exception handler class gives an ErroDTO which contains a Code, and a description.</p>
  
  <p>So the problem is there are 3 things, which give 3 different error responses, and I don't know how can I handle this, in Frontend which is an Angular project. </p>
  
  <p>I would like to handle all errors and exceptions by my ErroDto class, but I don't know how to transform the Identity or Attribute errors. </p>
  
  <p>I think that I could test the email and password validation directly in the endpoint instead of using Attribute, and I could test if the existing email, and the Identity won't be throw error. But I think it is not the best practice, and it will be a lot of boilerplate code.</p>
  
  <p>This is my exception handling class:</p>
  
  <pre><code>public class ErrorHandlingMiddleware
      {
          private readonly RequestDelegate next;
          public ErrorHandlingMiddleware(RequestDelegate next)
          {
              this.next = next;
          }
  
          public async Task Invoke(HttpContext context /* other dependencies */)
          {
              try
              {
                  await next(context);
              }
              catch (Exception ex)
              {
                  await HandleExceptionAsync(context, ex);
              }
          }
  
          private static Task HandleExceptionAsync(HttpContext context, Exception ex)
          {
              var code = HttpStatusCode.InternalServerError; // 500 if unexpected
  
              ErrorDto error = new ErrorDto();
  
              if (ex is WrongCredentialsException)
              {
                  code = HttpStatusCode.OK;
  
                  WrongCredentialsException wrongCredentialsException = (WrongCredentialsException) ex;
  
                  error.Code = wrongCredentialsException.Code;
                  error.Description = wrongCredentialsException.Message;
              }
  
              var result = JsonConvert.SerializeObject(new { error });
  
  
              context.Response.ContentType = "application/json";
              context.Response.StatusCode = (int)code;
              return context.Response.WriteAsync(result);
          }
      }
  </code></pre>