Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Servicestack - Write all exceptions to custom logger

I am trying to find how to catch all exceptions (raised on the server, not the client) from my ServiceStack services in order to write them to my custom logger (which writes it to the eventlog). Now I am confused what implementation to use. I find postings implementing a custom ServiceRunner which looks rather complicated.

I found in the documentation you can use something like:

public override void Configure(Funq.Container container)
{
    this.ServiceExceptionHandler = (req, ex) => { WRITE EXCEPTION TO MY OWN LOGGER };
}

Now I am stuck because this method is not available (there is a collection named ServiceExceptionHandlers, note the 's' at the end).

like image 573
Stackbever Avatar asked Mar 21 '23 01:03

Stackbever


1 Answers

You need to use the .Add method on the ServiceExceptionHandler because you can setup more than one handler, i.e. if you have multiple loggers. See here for more information.

You need two methods to catch all exceptions. One to catch the exceptions in your service, and one to catch the others. The code below shows how to handle both cases.

public override void Configure(Container container)
{
    //Handle Exceptions occurring in Services:
    this.ServiceExceptionHandler.Add((httpReq, request, exception) => {
        // Log your exceptions here
        ...
        // Call the default exception handler or prepare your own custom response
        return DtoUtils.CreateErrorResponse(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);
    };
}

Note:

The reason that ServiceStack is expecting a collection of handlers, and your example code didn't show this, is because that documentation is for v3 (BSD open source version of ServiceStack), the corresponding documentation is here, but you are running ServiceStack v4 (Commercial) where improvements have been made to allow multiple actions to be taken.

Hope this helps.

like image 90
Scott Avatar answered Apr 07 '23 04:04

Scott