c# - Filter Exception Stack Trace from Web API Error? -


i have web api communicate with.

when exception occurs, following json template:

{   "message": "an error has occurred.",   "exceptionmessage": "index outside bounds of array.",   "exceptiontype": "system.indexoutofrangeexception",   "stacktrace": "   @ webapitest.testcontroller.post(uri uri) in c:\\temp\\webapitest\\webapitest\\testcontroller.cs:line 18\r\n   @ system.web.http.controllers.reflectedhttpactiondescriptor.actionexecutor.<>c__displayclassf.<getexecutor>b__9(object instance, object[] methodparameters)\r\n   @ system.web.http.controllers.reflectedhttpactiondescriptor.actionexecutor.execute(object instance, object[] arguments)\r\n   @ system.threading.tasks.taskhelpers.runsynchronously[tresult](func`1 func, cancellationtoken cancellationtoken)" } 

what want json include "message" , "exceptionmessage" properties, still have control on returning full stack trace on demand.

i've tried using

globalconfiguration.configuration.includeerrordetailpolicy 

but seems it's or nothing, either single "message" property or getting full object when setting "always".

any easy way achieve this?

assistance appreciated.

in code use exception filters asking for, check following 2 links more details

web api exception handling

web api global error handling

what in our code follows:

  1. create exception filter:

    public class viewrexceptionfilterattribute : exceptionfilterattribute { // global context message modifying context response in case of exception private string globalhttpcontextmessage;  /// <summary> ///     overriding onexception method part of filter, detect type of action , ///     accordingly modify http ///     context response /// </summary> /// <param name="context"></param> public override void onexception(httpactionexecutedcontext context) {     // dictionary type , action various type actions, current method called various types     dictionary<type, action> dictionaryexceptiontypeaction = new dictionary<type, action>();      // add action given exception type     dictionaryexceptiontypeaction.add(typeof (viewrclientexception), viewrclientexceptionaction(context.exception));                 dictionaryexceptiontypeaction.add(typeof (exception), systemexceptionaction(context.exception));      // execute action given exception type     if (context.exception viewrclientexception)         dictionaryexceptiontypeaction[typeof (viewrclientexception)]();    else         dictionaryexceptiontypeaction[typeof (exception)]();      // reset context response using global string set in exception specific action     context.response = new httpresponsemessage     {         content = new stringcontent(globalhttpcontextmessage)     }; }  /// <summary> ///     action method viewrclientexception, creates exception message, json serialized /// </summary> /// <returns></returns> private action viewrclientexceptionaction(exception viewrexception) {     return (() =>     {         logexception(viewrexception);          viewrclientexception currentexception = viewrexception viewrclientexception;          exceptionmessageui exceptionmessageui = new exceptionmessageui();          exceptionmessageui.errortype = currentexception.errortypedetail;          exceptionmessageui.errordetaillist = new list<errordetail>();          foreach (clienterror clienterror in currentexception.clienterrorentity)         {             errordetail errordetail = new errordetail();              errordetail.errorcode = clienterror.errorcode;              errordetail.errormessage = clienterror.errormessage;              exceptionmessageui.errordetaillist.add(errordetail);         }          globalhttpcontextmessage = jsonconvert.serializeobject(exceptionmessageui, formatting.indented);     }); } 

here viewrclientexception custom exception class following schema:

public class viewrclientexception : exception {     public viewrclientexception(errortype errortype, list<clienterror> errorentity)     {         errortypedetail = errortype;         clienterrorentity = errorentity;     }      public errortype errortypedetail { get; private set; }     public list<clienterror> clienterrorentity { get; private set; } } 

action method defined above ensures relevant json serialized string, can used json response, similar job of systemexceptionaction generic exception, not custom. in fact have many other custom exception categories. current filter modifies httpcontext.response

  1. register exception filter in webapiconfig.cs, shown below:

      public static class webapiconfig     {       public static void register(httpconfiguration config)       {         // web api configuration , services          // adding generic exception filter application         config.filters.add(new viewrexceptionfilterattribute());          // web api routes         config.maphttpattributeroutes();          config.routes.maphttproute("controlleractionapi", "api/{controller}/{action}/{userid}",             new {userid = routeparameter.optional}             );          config.routes.maphttproute("controllerapi", "api/{controller}/{userid}",             new {userid = routeparameter.optional}             );       }    } 

now should work providing custom message need


Comments