Custom exception handling in ServiceStack REST service

后端 未结 2 1507
孤城傲影
孤城傲影 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:08

    I made improvements to @mythz' answer.

    public override void Configure(Container container) {
        //Handle Exceptions occurring in Services:
    
        this.ServiceExceptionHandlers.Add((httpReq, request, exception) = > {
            //log your exceptions here
            ...
            //call default exception handler or prepare your own custom response
            return DtoUtils.CreateErrorResponse(request, exception);
        });
    
        //Handle Unhandled Exceptions occurring outside of Services
        //E.g. Exceptions during Request binding or in filters:
        this.UncaughtExceptionHandlers.Add((req, res, operationName, ex) = > {
            res.Write("Error: {0}: {1}".Fmt(ex.GetType().Name, ex.Message));
    
    #if !DEBUG
            var message = "An unexpected error occurred."; // Because we don't want to expose our internal information to the outside world.
    #else
            var message = ex.Message;
    #endif
    
            res.WriteErrorToResponse(req, req.ContentType, operationName, message, ex, ex.ToStatusCode()); // Because we don't want to return a 200 status code on an unhandled exception.
        });
    }
    

提交回复
热议问题