ServiceExceptionHandler usage on RestServiceBase<T>

假如想象 提交于 2019-12-29 07:53:28

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/13058205/serviceexceptionhandler-usage-on-restservicebaset

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!