Custom exception handling in ServiceStack REST service

后端 未结 2 1508
孤城傲影
孤城傲影 2021-01-05 14:04

I have a ServiceStack REST service and I need to implement custom error handling. I\'ve been able to customize service errors by setting AppHostBase.ServiceExceptionHandler

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-05 14:25

    The AppHostBase.ServiceExceptionHandler global handler only handles service exceptions. To handle exceptions occurring outside of services you can set the global AppHostBase.ExceptionHandler handler, e.g:

    public override void Configure(Container container)
    {
        //Handle Exceptions occurring in Services:
        this.ServiceExceptionHandler = (request, exception) => {
    
            //log your exceptions here
            ...
    
            //call default exception handler or prepare your own custom response
            return DtoUtils.HandleException(this, request, exception);
        };
    
        //Handle Unhandled Exceptions occurring outside of Services, 
        //E.g. in Request binding or filters:
        this.ExceptionHandler = (req, res, operationName, ex) => {
             res.Write("Error: {0}: {1}".Fmt(ex.GetType().Name, ex.Message));
             res.EndServiceStackRequest(skipHeaders: true);
        };
    }
    

    To create and serialize a DTO to the response stream in the non-service ExceptionHandler you would need to access and use the correct serializer for the request from IAppHost.ContentTypeFilters.

    More details about is in the Error Handling wiki page.

提交回复
热议问题