title: What is the best possible way to send custom error responses in .net core web api
body: <p>I'm making a .net Core WebApi using <code>.Net Core 2.2</code>. The API is ready but the failure message and response is where I'm stuck at. </p>
  
  <p>Right now, I'm getting respose like below</p>
  
  <p>json</p>
  
  <pre><code>{
      "empId":1999,
      "empName":"Conroy, Deborah",
      "enrollmentStatus":true,
      "primaryFingerprintScore":65,
      "secondaryFingerprintScore":60,
      "primaryFingerprint":null,
      "secondaryFingerprint":null,
      "primaryFingerprintType":null,
      "secondaryFingerprintType":null}
  }
  </code></pre>
  
  <p>I created a json formatter class  and wrote the below code</p>
  
  <pre><code>public class SuperJsonOutputFormatter : JsonOutputFormatter
  {
      public SuperJsonOutputFormatter(
          JsonSerializerSettings serializerSettings,
          ArrayPool&lt;char&gt; charPool) : base(serializerSettings, charPool)
      {
      } 
  
      public override async Task WriteResponseBodyAsync(
          OutputFormatterWriteContext context,
          Encoding selectedEncoding)
      {
  
          if (context == null)
              throw new ArgumentNullException(nameof(context));
          if (selectedEncoding == null)
              throw new ArgumentNullException(nameof(selectedEncoding));
          using (TextWriter writer =
              context.WriterFactory(
                  context.HttpContext.Response.Body,
                  selectedEncoding))
          {
  
              var rewrittenValue = new
              {
                  resultCode = context.HttpContext.Response.StatusCode,
                  resultMessage =
                  ((HttpStatusCode)context.HttpContext.Response.StatusCode)
                      .ToString(),
                  result = context.Object
              };
  
              this.WriteObject(writer, rewrittenValue);
              await writer.FlushAsync();
          }
      }
  </code></pre>
  
  <p>I expect all the error codes to be sent as generic error messages like the JSON below.</p>
  
  <p>FOR STATUS OKAY:</p>
  
  <pre><code>{
      "status" : True,
      "error"  : null,
      "data" : {
          {
              "empId":1999,
              "empName":"Conroy, Deborah",
              "enrollmentStatus":true,
              "primaryFingerprintScore":65,
              "secondaryFingerprintScore":60,
              "primaryFingerprint":null,
              "secondaryFingerprint":null,
              "primaryFingerprintType":null,
              "secondaryFingerprintType":null}
          }
      }   
  }
  </code></pre>
  
  <p>FOR OTHER STATUS LIKE 404, 500, 400, 204 </p>
  
  <pre><code>{
      "status" : False,
      "error"  : {
          "error code" : 404,
          "error description" : Not Found
      },
      "data" : null   
  }
  </code></pre>