title: How to Gracefully Throw Exceptions in Custom Content Neogtiation Formatters in .NET Core
body: <p>So I am building out a custom content negotiation formatter <a href="https://github.com/dotnet/AspNetCore.Docs/blob/master/aspnetcore/web-api/advanced/custom-formatters/sample/Formatters/VcardOutputFormatter.cs" rel="nofollow noreferrer">like this</a> for a custom data format that we need to use in our .NET Core API.</p>
  
  <pre class="lang-cs prettyprint-override"><code>using Microsoft.AspNetCore.Mvc.Formatters;
  using Microsoft.AspNetCore.Http;
  using System;
  using System.Collections.Generic;
  using System.Threading.Tasks;
  using System.Text;
  using CustomFormatterDemo.Models;
  using Microsoft.Net.Http.Headers;
  using System.Reflection;
  using Microsoft.Extensions.Logging;
  
  namespace CustomFormatterDemo.Formatters
  {
      #region classdef
      public class VcardOutputFormatter : TextOutputFormatter
      #endregion
      {
          #region ctor
          public VcardOutputFormatter()
          {
              SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("text/vcard"));
  
              SupportedEncodings.Add(Encoding.UTF8);
              SupportedEncodings.Add(Encoding.Unicode);
          }
          #endregion
  
          #region canwritetype
          protected override bool CanWriteType(Type type)
          {
              if (typeof(Contact).IsAssignableFrom(type) 
                  || typeof(IEnumerable&lt;Contact&gt;).IsAssignableFrom(type))
              {
                  return base.CanWriteType(type);
              }
              return false;
          }
          #endregion
  
          #region writeresponse
          public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
          {
              IServiceProvider serviceProvider = context.HttpContext.RequestServices;
              var logger = serviceProvider.GetService(typeof(ILogger&lt;VcardOutputFormatter&gt;)) as ILogger;
  
              var response = context.HttpContext.Response;
  
              var buffer = new StringBuilder();
              if (context.Object is IEnumerable&lt;Contact&gt;)
              {
                  foreach (Contact contact in context.Object as IEnumerable&lt;Contact&gt;)
                  {
                      FormatVcard(buffer, contact, logger);
                  }
              }
              else
              {
                  var contact = context.Object as Contact;
                  FormatVcard(buffer, contact, logger);
              }
              await response.WriteAsync(buffer.ToString());
          }
  
          private static void FormatVcard(StringBuilder buffer, Contact contact, ILogger logger)
          {
              buffer.AppendLine("BEGIN:VCARD");
              buffer.AppendLine("VERSION:2.1");
              buffer.AppendFormat($"N:{contact.LastName};{contact.FirstName}\r\n");
              buffer.AppendFormat($"FN:{contact.FirstName} {contact.LastName}\r\n");
              buffer.AppendFormat($"UID:{contact.ID}\r\n");
              buffer.AppendLine("END:VCARD");
              logger.LogInformation("Writing {FirstName} {LastName}", contact.FirstName, contact.LastName);
          }
          #endregion
      }
  }
  </code></pre>
  
  <p>Obviously, I can just do something like <code>throw new Exception("this doesn't work")</code>, but that is just going to give the API consumer a 500 response. Curious how I can throw more graceful errors with particular codes or, at the very least, the error details for the 500 status.</p>