-->

ServiceStack - how to disable default exception lo

2020-05-01 02:22发布

问题:

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.HandleException, like this:

private object LogServiceException(object request, Exception exception)
{
    var message = string.Format("Here we make a custom message...");
    _logger.Error(message, exception);
    return DtoUtils.HandleException(this, request, exception);
 }

This results in the error being logged twice, since DTOUtils.HandleException also logs it, in a less customised format. Yes, I much prefer this to the DTOUtils logging and don't want to just use that.

How do we turn off DTOUtils logging while retaining the rest of the functionality? Nobody likes getting twice as many error emails as they should.

回答1:

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<TRequest> CreateServiceRunner<TRequest>(ActionContext      actionContext)
          {
               return new MyServiceRunner<TRequest>(this, actionContext);
            }  

in the ServiceRunner class

       public class MyServiceRunner<T> : ServiceRunner<T>
       {

            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<ResponseError>();
                             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; 
               }
            }


回答2:

Do not call DtoUtils.HandleException as it logs the error. Don't call ServiceRunner.HandleException either, it calls DtoUtils.HandleException.

Call DtoUtils.CreateErrorResponse to make the response (it is used by DtoUtils.HandleException). The ToResponseStatus helper is also in DtoUtils

My AppServiceRunner is now like this:

public class AppServiceRunner<T> : ServiceRunner<T>
{
    public AppServiceRunner(AppHost appHost, ActionContext actionContext)
        : base(appHost, actionContext)
    {
    }

    public override object HandleException(IRequestContext requestContext,
        T request, Exception ex)
    {   
        LogException(requestContext, request, ex);

        var responseStatus = ex.ToResponseStatus();
        return DtoUtils.CreateErrorResponse(request, ex, responseStatus);
    }

    private void LogException(IRequestContext requestContext, T request, Exception ex)
    {
        // since AppHost.CreateServiceRunner can be called before AppHost.Configure
        // don't get the logger in the constructor, only make it when it is needed
        var logger = MakeLogger();
        var requestType = typeof(T);
        var message = string.Format("Exception at URI:'{0}' on service {1} : {2}",
            requestContext.AbsoluteUri, requestType.Name, request.ToJson());

        logger.Error(message, ex);
    }

    private static ILog MakeLogger()
    {
        return LogManager.GetLogger(typeof(AppServiceRunner<T>));
    }
}

Now the only service errors that I get are those generated by this code.