Using ServiceExceptionHandler in RestServiceBase <T>

I am trying to use ServiceExceptionHandleron my serivce which extendsRestServiceBase<TViewModel>

I can use AppHost.ServiceExceptionHandlerthat which works fine. I need user information from HttpRequestwhich is not available at the AppHost level.

So, I'm trying to use ServiceExceptionHandlerat the service level. Although I set the delegate to the service ctor, it nullis when an exception is thrown by a methodOnGet

public class StudentService : RestServiceBase<Student>
{ 
    public StudentService()
    {
        ServiceExceptionHandler = (request, exception) =>
        {
            logger.Error(string.Format("{0} - {1} \n Request : {2}\n", HttpRequest.UserName(), exception.Message, request.Dump()), exception);
            var errors = new ValidationErrorField[] { new ValidationErrorField("System Error", "TODO", "System Error") };
            return DtoUtils.CreateErrorResponse("System Error", "System Error", errors);
        };
    }
}

I am not sure what the problem is with this code. Any help would be appreciated.

+4
source share
1 answer

Register global application AppHost.ServiceExceptionHandler

AppHost.Configure() :

this.ServiceExceptionHandler = (request, ex) => {
   ... //handle exception and generate your own ErrorResponse
};

:

API

API, , , :

public class AppHost { 
  ...
    public virtual IServiceRunner<TRequest> CreateServiceRunner<TRequest>(
        ActionContext actionContext)
    {           
        //Cached per Service Action
        return new ServiceRunner<TRequest>(this, actionContext); 
    }
}

public class MyServiceRunner<T> : ServiceRunner<T> {
    public override object HandleException(
        IRequestContext requestContext, TRequest request, Exception ex) {
      // Called whenever an exception is thrown in your Services Action
    }
}

API

RestServiceBase<T> API, , HandleException, :

public class StudentService : RestServiceBase<Student>
{ 
    ...

    protected override object HandleException(T request, Exception ex)
    {
        LogException(ex);

        return base.HandleException(request, ex);
    }
} 
+6

All Articles