ServiceStack - how to disable default exception logging

前端 未结 2 1079
故里飘歌
故里飘歌 2021-01-23 15:49

In line with the ServiceStack documentation, we have a global service exception handler. The docs say that this handler should log the exception then call DtoUtils.HandleE

2条回答
  •  星月不相逢
    2021-01-23 16:04

    I hope the following code solves your problem.

    based on the documentation New API, Custom Hooks, ServiceRunner

    and Fine grain error handling using the New API's ServiceRunner

    in AppHost.Configure

       LogManager.LogFactory = new ServiceStack.Logging.Support.Logging.ConsoleLogFactory();   
    

    then in AppHost class

             public override IServiceRunner CreateServiceRunner(ActionContext      actionContext)
              {
                   return new MyServiceRunner(this, actionContext);
                }  
    

    in the ServiceRunner class

           public class MyServiceRunner : ServiceRunner
           {
    
                public override object HandleException(IRequestContext requestContext, T request, Exception ex)
                  {
                      if ( isYourCondition ) 
                      {
                            ResponseStatus rs = new ResponseStatus("error1", "your_message");
                            // optionally you can add custom response errors
                                 rs.Errors = new List();
                                 rs.Errors.Add(new ResponseError());
                                 rs.Errors[0].ErrorCode = "more details 2";
    
                                // create an ErrorResponse with the ResponseStatus as parameter
                                var errorResponse = DtoUtils.CreateErrorResponse(request, ex, rs);
                                 // log the error
                                 Log.Error("your_message", ex);
                                 return errorResponse;
    
                       }
                       else
                            return base.HandleException(requestContext, request, ex);
                   }
    
                }
    

    if you return the base.HandleException, it calls internally the DtoUtils.HandleException. You will see in console, one log error only.

    In client, if you handle the WebServiceException for custom errors.

                catch (WebServiceException err)
                {
                    if ( err.ResponseStatus.Errors != null)
                   { // do something with err.ResponseStatus.Errors[0].ErrorCode; 
                   }
                }
    

提交回复
热议问题