ServiceExceptionHandler usage on RestServiceBase

前端 未结 1 1038
挽巷
挽巷 2020-12-19 15:37

I\'m trying to use the ServiceExceptionHandler on my Serivce which extends RestServiceBase

I can use the AppHost.Se

相关标签:
1条回答
  • 2020-12-19 15:54

    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);
        }
    } 
    
    0 讨论(0)
提交回复
热议问题