Created
October 28, 2014 18:43
-
-
Save dgwaldo/1ed4e107dab68fcc533d to your computer and use it in GitHub Desktop.
Example of WebAPI 2 Exception Filter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class WebApiConfig{ | |
public static void Register(HttpConfiguration config) | |
{ | |
#if DEBUG | |
config.Filters.Add(new DebugGeneralExceptionAttribute()); | |
#endif | |
webApiConfig . Filters. Add( new DbEntityValidationExceptionAttribute ()); | |
// Other configuration code... | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class DebugGeneralExceptionAttribute : ExceptionFilterAttribute | |
{ | |
public override void OnException( HttpActionExecutedContext context) | |
{ | |
var messageParsedOfNewLineEtc = Regex .Replace(context . Exception. Message, @"\t|\n|\r" , "" ); | |
var response = new HttpResponseMessage ( HttpStatusCode. InternalServerError) | |
{ | |
Content = new StringContent(context . Exception. Message), | |
ReasonPhrase = "Something has gone terribly wrong :( " + messageParsedOfNewLineEtc | |
}; | |
context . Response = response; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment