Poor man display errors–part 2 – API

The idea of previous post was that I want to display the errors from a WebApplication – composed by a backend ( WebAPI .NET Core )and frontend( Blazor )

In this post I will show what modifications I must do in the API – code in .NET Core . There are 3 steps

Step1 : Intercept Errors

First I should intercept ( via a middleware ) all errors that can occur in an WebAPI.



using NLog.Web;

namespace XP.API;

public class LogErrorsMiddleware : IMiddleware
{
    static LogErrorsMiddleware()
    {
        logger = NLog.LogManager.GetCurrentClassLogger();
    }
    private static NLog.Logger logger;

    public LogErrorsMiddleware()
    {
        
    }
    public Task InvokeAsync(HttpContext context, RequestDelegate next)
    {
        try
        {
            logger.Debug("Starting "+ context.Request.Path);
            return next(context);

        }
        catch(Exception ex)
        {
            // Log the exception
            logger.Error(ex, "An error occurred while processing the request.");
            
            throw;
        }
        finally
        {
            logger.Debug("Ending " + context.Request.Path);
        }
    }
}

And I register in program.cs

builder.Services.AddTransient<LogErrorsMiddleware>();
//other statemtents
app.UseMiddleware<XP.API.LogErrorsMiddleware>();

Step2 : Add errors to memory

Now we should register the errors from the logging framework into the memory . NLog has a target for registering in memory
( https://github.com/NLog/NLog/wiki/Memory-target ) . ( Serilog has https://github.com/serilog-contrib/SerilogSinksInMemory)

So this is the nlog xml


<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" autoReload="true" throwConfigExceptions="true" internalLogLevel="Info" internalLogFile="c:\temp\internal-nlog-AspNetCore.txt">

	<!-- enable asp.net core layout renderers -->
	<extensions>
		<add assembly="NLog.Web.AspNetCore"/>
	</extensions>

	<!-- the targets to write to -->
	<targets>
		<target xsi:type="Memory" name="stringData" MaxLogsCount="200" layout="${longdate}|${aspnet-user-isauthenticated}|${aspnet-user-identity}|${level:uppercase=true}|${logger}|${message:withexception=true}" />
		<!-- File Target for all log messages with basic details -->
		<target xsi:type="File" name="allfile" fileName="c:\temp\nlog-AspNetCore-all-${shortdate}.log" layout="${longdate}|${event-properties:item=EventId:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}" />

		<!-- File Target for own log messages with extra web details using some ASP.NET core renderers -->
		<target xsi:type="File" name="ownFile-web" fileName="c:\temp\nlog-AspNetCore-own-${shortdate}.log" layout="${longdate}|${event-properties:item=EventId:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />

		<!--Console Target for hosting lifetime messages to improve Docker / Visual Studio startup detection -->
		<target xsi:type="Console" name="lifetimeConsole" layout="${MicrosoftConsoleLayout}" />
	</targets>

	<!-- rules to map from logger name to target -->
	<rules>
		<!-- All logs, including from Microsoft -->
		<!--<logger name="*" minlevel="Trace" writeTo="allfile" />-->

		<!-- Suppress output from Microsoft framework when non-critical -->
		<logger name="System.*" finalMinLevel="Warn" />
		<logger name="Microsoft.*" finalMinLevel="Warn" />
		<!-- Keep output from Microsoft.Hosting.Lifetime to console for fast startup detection -->
		<logger name="Microsoft.Hosting.Lifetime*" finalMinLevel="Info" writeTo="lifetimeConsole" />
		<logger name="*" minLevel="Trace" writeTo="lifetimeConsole" />
		<logger name="*" minLevel="Error" writeTo="stringData" />
		<!--<logger name="*" minLevel="Trace" writeTo="ownFile-web" />-->
	</rules>
</nlog>

Step3 : Expose Errors

Now we should expose the API to the outside world. I have considered 2 API, one for retrieving and the other for clearing

app.MapGet("/nlog/memory/{name:alpha}/list", (string name) =>
{
    var target = LogManager.Configuration.FindTargetByName<MemoryTarget>(name);
    var logEvents = target.Logs;
    return logEvents.Select((line, nr) => new
    {
        nr = (nr+1),
        line,

    }).ToArray();
});
    app.MapGet("/nlog/memory/{name}/clear", (string name) =>
    {
        var target = LogManager.Configuration.FindTargetByName<MemoryTarget>(name);
        var logEvents = target.Logs;
        var nr = logEvents.Count;
        logEvents.Clear();
        return (nr.ToString());
    })
    //.ShortCircuit() 
    .WithTags("andrei");

In part three, we’ll explore how to call these endpoints from your Blazor frontend and display errors in a user-friendly way.