WebAPI Exception Handling

Posted by Joe Enos on May 12, 2021 · 4 mins read

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Filters;
using Newtonsoft.Json;

namespace MvcApplication2.Controllers
{
public class FooController : ApiController
{
[HttpPost]
[ExcHand]
public async Task<GetFooResponse> GetFoo(GetFooRequest request)
{
throw new ApplicationException("Fail - you suck");
return new GetFooResponse
{
Foo = new Foo { Message = "Hello " + request.Name }
};
}
}

public class Foo
{
public string Message { get; set; }
}

public class GetFooRequest
{
public string Name { get; set; }
}

public class BaseResponse
{
public string ErrorMessage { get; set; }
}

public class GetFooResponse
: BaseResponse
{
public Foo Foo { get; set; }
}

public class ExcHandAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
var responseObject = (BaseResponse)Activator.CreateInstance(actionExecutedContext.ActionContext.ActionDescriptor.ReturnType);
responseObject.ErrorMessage = actionExecutedContext.Exception.ToString();
var msg = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(JsonConvert.SerializeObject(responseObject))
};
actionExecutedContext.Response = msg;
}
}
}