4

I'm trying to use the ServiceExceptionHandler on my Serivce which extends RestServiceBase<TViewModel>

I can use the AppHost.ServiceExceptionHandler, that's working fine. I need the user info from the HttpRequest, thats not available at AppHost level.

So I'm trying to use the ServiceExceptionHandler on Service level. Though I set the delegate on service ctor, it's null when exception thrown on OnGet method

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'm not sure of what is the issue with this code. Any help will be appreciated.

Scott
  • 21,211
  • 8
  • 65
  • 72
Sathish Naga
  • 1,366
  • 2
  • 10
  • 18

1 Answers1

6

Register Global AppHost.ServiceExceptionHandler

In your AppHost.Configure() you can register a global Exception handler with:

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

For finer-grained Exception handlers you can override the following custom service event hooks:

Handling Exceptions with the New API

If you're using the New API you can override the Exception by providing a custom runner, e.g:

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
    }
}

Handling Exceptions with the Old API

RestServiceBase<T> is uses the old API in which you can handle errors by overriding the HandleException method, e.g:

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

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

        return base.HandleException(request, ex);
    }
} 
mythz
  • 141,670
  • 29
  • 246
  • 390