Skip to content

Instantly share code, notes, and snippets.

@kenstone
Created September 19, 2012 16:46
Show Gist options
  • Select an option

  • Save kenstone/3750711 to your computer and use it in GitHub Desktop.

Select an option

Save kenstone/3750711 to your computer and use it in GitHub Desktop.

Revisions

  1. David Iffland created this gist Sep 19, 2012.
    50 changes: 50 additions & 0 deletions FailRequestAttribute.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,50 @@
    using System;
    using System.Net;
    using System.Threading;
    using System.Net.Http;
    using System.Web.Http;
    using System.Web.Http.Controllers;
    using ActionFilterAttribute = System.Web.Http.Filters.ActionFilterAttribute;


    namespace MyProject
    {
    /// <summary>
    /// Always fails the current HttpRequestMessage. Used for error handling development in front-end UIs.
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public class FailRequestAttribute : ActionFilterAttribute
    {
    /// <summary>
    /// The HttpStatusCode to include in the error response.
    /// </summary>
    public HttpStatusCode StatusCode = HttpStatusCode.InternalServerError;

    /// <summary>
    /// An error message to be sent in the description of the error.
    /// </summary>
    public string ErrorMessage;

    /// <summary>
    /// How long of a delay to introduce before the error occurs. Use to simulate timeouts.
    /// </summary>
    public int Delay = 0;

    private const string DefaultErrorMessage = "Automatic error generated. This is caused by the FailRequest ActionFilter. To stop this error, remove the attribute from the class or method.";

    public override void OnActionExecuting(HttpActionContext filterContext)
    {

    if (ErrorMessage == null)
    {
    ErrorMessage = string.Format("{0}. This error was fired on the {1} Action of the {2} Controller.",
    DefaultErrorMessage, filterContext.ActionDescriptor.ActionName,
    filterContext.ActionDescriptor.ControllerDescriptor.ControllerName);
    }

    Thread.Sleep(Delay);

    throw new HttpResponseException(filterContext.Request.CreateErrorResponse(StatusCode, ErrorMessage));
    }
    }
    }