在ServiceStack应用程序中使用时,应用程序洞察力不会跟踪异常



i当前有一个问题,即应用程序洞察力没有显示.NET Core中的例外。我也在使用ServiceStackCore来构建我的API。

这就是应用程序Insights下的Azure Portal中当前的样子:Azure Portal的屏幕截图

您可以看到,响应代码全部显示400、403、500。但是,没有例外:

我找到了一条圆形路线来获得例外:

var telemetry = new TelemetryClient();
...
try
{ ...
}
catch (Exception ex)
{
   telemetry.TrackException(ex);
}
  • 我想知道Servicestack是否有任何内置的异常处理,可能会被应用程序见解所捕获的异常吗?

  • ,如果有任何包装盒配置可以在应用程序见解中完成以显示这些异常而无需添加try-catch块?

ServiceStack允许您注册处理程序来处理异常:

public override void Configure(Container container)
{
    //Handle Exceptions occurring in Services:
    this.ServiceExceptionHandlers.Add((httpReq, request, exception) => {
        //log your exceptions here
        ...
        return null; //continue with default Error Handling
        //or return 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: {ex.GetType().Name}: {ex.Message}");
         res.EndRequest(skipHeaders: true);
    });
}

ServiceExceptionHandlers被解雇用于服务例外,而 UncaughtExceptionHandlers则针对非或未知服务请求发射。

谢谢您的回答并添加更多的清晰度:

我一直在覆盖Apphost中的handsuncaughtexception方法以及Apphost中的ResolverSponseException方法,以便

  • 将序列化错误作为不良请求
  • 消毒例外,我不想暴露于客户端(作为内部服务器错误(

    private TelemetryClient telemetry = new TelemetryClient();
    public override void HandleUncaughtException(IRequest httpReq, IResponse httpRes, string operationName, Exception ex)
    {
        telemetry.TrackException(ex);
        if (!(ex is SerializationException))
        { // don't handle like BadRequest if not serialization exception
            base.HandleUncaughtException(httpReq, httpRes, operationName, ex);
            return;
        }
        httpRes.WriteError(new HttpError(HttpStatusCode.BadRequest, ex.InnerException?.Message), (int)HttpStatusCode.BadRequest);
        httpRes.EndRequest(skipHeaders: true);
    }
    public override Exception ResolveResponseException(Exception ex)
    {
        telemetry.TrackException(ex);
        if (ex.GetType() == typeof(HttpError))
        { // Exception thrown using HttpError, do not sanitize
            return ex;
        }
        return new HttpError(HttpStatusCode.InternalServerError, "The service has encountered an error, please contact your account manager if this persists.");
    }
    

,我还为这两种方法添加了Trackexception((遥测,这将导致例外被跟踪到App Insights。

我认为ServiceStack在某种程度上抑制了出现在App Insights中的例外,并且该实现将解决此问题。我认为这可能发生的原因是因为我还有另一个没有ServiceStack(IdentityServer(的API,该API正确跟踪了例外。

最新更新