Last active
April 22, 2022 05:10
-
-
Save RickyLin/e99a1867419a4e6e24552db8d791e42b to your computer and use it in GitHub Desktop.
Append command text and parameters to Exception.Data property when exceptions are thrown from Entity Framework Core.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
using Microsoft.EntityFrameworkCore.Diagnostics; | |
using System; | |
using System.Collections.Generic; | |
using System.Data.Common; | |
using System.Threading; | |
using System.Threading.Tasks; | |
*/ | |
public class EnrichExceptionDataDbCommandInterceptor : DbCommandInterceptor | |
{ | |
public static readonly EnrichExceptionDataDbCommandInterceptor Instance = new(); // this type is stateless, so it can be singleton. | |
protected EnrichExceptionDataDbCommandInterceptor() { } | |
public override void CommandFailed(DbCommand command, CommandErrorEventData eventData) | |
{ | |
PopulateExceptionData(command, eventData); | |
} | |
public override Task CommandFailedAsync(DbCommand command, CommandErrorEventData eventData, CancellationToken cancellationToken = default) | |
{ | |
PopulateExceptionData(command, eventData); | |
return Task.CompletedTask; | |
} | |
private void PopulateExceptionData(DbCommand command, CommandErrorEventData eventData) | |
{ | |
eventData.Exception.Data.Add("Command Text", command.CommandText); | |
if (command.Parameters.Count > 0) | |
{ | |
var paramTypes = new List<string>(command.Parameters.Count); | |
var paramValues = new List<string>(command.Parameters.Count); | |
string? paramValue; | |
foreach (DbParameter p in command.Parameters) | |
{ | |
paramTypes.Add($"{p.ParameterName}: {p.DbType}, {p.Size}, {p.Direction}, {p.Scale}, {p.Precision}"); | |
if (p.Value == null) | |
{ | |
paramValue = "[null]"; | |
} | |
else if (p.Value is DateTime dt) | |
{ | |
paramValue = dt.ToString("yyyy-MM-dd HH:mm:ss"); | |
} | |
else | |
{ | |
paramValue = p.Value.ToString(); | |
} | |
paramValues.Add($"{p.ParameterName}: {paramValue}"); | |
} | |
eventData.Exception.Data.Add("Parameter Types", string.Join(Environment.NewLine, paramTypes)); | |
eventData.Exception.Data.Add("Parameter Values", string.Join(Environment.NewLine, paramValues)); | |
} | |
} | |
} | |
/* Usage: | |
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) | |
{ | |
if (optionsBuilder.IsConfigured) | |
return; | |
optionsBuilder.AddInterceptors(EnrichExceptionDataDbCommandInterceptor.Instance); | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment