带有通用记录器参数的 .NET Core 3 ExceptionHandler - AmbiguousMatchException
.NET Core 3 ExceptionHandler with Generic Logger parameter - AmbiguousMatchException
我正在尝试为一个 API 项目实施 .NET Core 3 app.UseExceptionHandler,但是每个 API 控制器都有一个通用记录器,我想将其传递给错误方法。例如,如果错误发生在我的 WorkingController 中,我希望 ILogger<WorkingController>
成为日志记录实体。我发现使用内置的 ExceptionHandler,我丢失了一些请求的上下文,如果可能的话我想捕获这个上下文。
这是我所有的 API 方法以前的样子:
[Route("api/working")]
[ApiController]
public class WorkingController
{
private readonly ILogger<WorkingController> _logger;
public WorkingController(ILogger<WorkingController> logger)
{
_logger = logger;
}
[Route("workingRoute")]
public IActionResult SomeMethod()
{
_logger.LogInformation("Starting SomeMethod");
try
{
// doing some stuff here
}
catch(Exception ex)
{
_logger.LogError(ex, "Something happened");
return Problem();
}
return Ok();
}
}
我尝试设置一个 BaseErrorController,其他控制器可以从中继承:
[ApiController]
public abstract class BaseErrorController<T> : ControllerBase
{
protected readonly ILogger<T> Logger;
public BaseErrorController(ILogger<T> logger)
{
Logger = logger;
}
[AllowAnonymous]
[Route("/error")]
public IActionResult Error()
{
var context = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
if (context != null)
{
var ex = context.Error;
Logger.LogError(ex, $"{context.Path} failed - {ex.Message}");
return Problem(
detail: context.Error.StackTrace,
title: context.Error.Message);
}
return Problem();
}
}
现在我以前的 WorkingController 看起来像这样,可以说它更干净(代码更少):
[Route("api/working")]
[ApiController]
public class WorkingController : BaseErrorController<WorkingController>
{
public WorkingController(ILogger<WorkingController> logger) : base(logger) { }
[Route("workingRoute")]
public IActionResult SomeMethod()
{
Logger.LogInformation("Starting SomeMethod");
// doing some stuff here
return Ok();
}
}
在 Startup.cs 中,我用 app.UseExceptionHandler("/error")
注册了这一切,它似乎工作正常。 . . except 现在在我的日志中,我看到以下错误(因为我有多个控制器实现了这个基本控制器):
An exception was thrown attempting to execute the error handler.
Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware
Microsoft.AspNetCore.Routing.Matching.AmbiguousMatchException: The request matched multiple endpoints.
Matches: Namespace.Controllers.WorkingController.Error (Namespace)
Namespace.Controllers.AnotherController.Error (Namespace)
at Microsoft.AspNetCore.Routing.Matching.DefaultEndpointSelector.ReportAmbiguity(CandidateState[] candidateState)
at Microsoft.AspNetCore.Routing.Matching.DefaultEndpointSelector.ProcessFinalCandidates(HttpContext httpContext, CandidateState[] candidateState)
at Microsoft.AspNetCore.Routing.Matching.DefaultEndpointSelector.Select(HttpContext httpContext, CandidateState[] candidateState)
at Microsoft.AspNetCore.Routing.Matching.DfaMatcher.MatchAsync(HttpContext httpContext)
at Microsoft.AspNetCore.Routing.Matching.DataSourceDependentMatcher.MatchAsync(HttpContext httpContext)
at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.HandleException(HttpContext context, ExceptionDispatchInfo edi)
有人知道这里的解决方案是什么吗? ExceptionHandler 是否存在过载,这可能正是我正在寻找的?这个解决方案是不是太精品了,我应该回到我之前做的事情?帮助我,Stack Overflow。谢谢!
不幸的是,根本没有 built-in 方法可以干净利落地做到这一点。你可以在这里找到一个包来帮助(我没看过),或者你可能想要 re-write ASP.NET 核心的某些部分,但我真的不想那样做。
还有另一种方法,根据您更喜欢哪个版本,recommended/recommended 反对,但我赞成前者。我没有在控制器级别出现 throwing/catching 异常,而是将控制器视为最愚蠢的东西,所以它们只是调用一些服务,仅此而已。
如果您想知道在何处引发了异常,或者您特别希望异常未被捕获,我的团队遵循的策略是创建自定义异常。然后您可以不捕获这些(并且 HTTP500 将返回给调用者)或者您可以有一个自定义中间件并在那里定义应该发生什么。
以下是一个示例,完全写在这里,因此可能需要进行一些更改,它只是为了演示一种可能的方法,而不是一个工作演示。
给定一些对您的域有效的例外情况:
public class UserNotFoundException : Exception { public Guid UserId { get; set; } }
public class InvalidModelException : Exception { }
还有一个异常处理程序:
public class MyCustomExceptionHandlerMiddleware
{
private readonly ILogger<MyCustomExceptionHandlerMiddleware> _logger;
public MyCustomExceptionHandlerMiddleware(ILogger<MyCustomExceptionHandlerMiddleware> logger)
{
_logger = logger;
}
public async Task Invoke(RequestDelegate next)
{
try
{
await next(); // without this, the request doesn't execute any further
}
catch (UserNotFoundException userNotFound)
{
_logger.LogError(userNotFound, "The user was not found");
// manipulate the response here, possibly return HTTP404
}
catch (Exception ex)
{
_logger.LogError(ex, "Something really bad happened");
// manipulate the response here
}
}
}
你可以有这样的东西:
public class UsersService : IUsersService
{
private readonly ILogger<UsersService> _logger;
private readonly UsersContext _context;
// assume UsersContext is an EntityFramework context or some database service
public UsersService(ILogger<UsersService> logger, UsersContext context)
{
_logger = logger;
_context = context;
}
public async Task<User> GetUserAsync(Guid userId)
{
try
{
if (userId == Guid.Empty)
{
throw new InvalidModelException();
}
var user = await _context.FindUserAsync(userId);
if (user == null)
{
throw new UserNotFoundException(userId);
}
return user;
}
catch (InvalidModelException invalidModel)
{
_logger.LogWarning("The received user id is empty");
return null;
}
}
}
及其对应的控制器:
public class UsersController : ControllerBase
{
private readonly IUsersService _usersService;
public UsersController(IUsersService usersService)
{
_usersService = usersService;
}
[HttpGet("userId:guid")]
public async Task<IActionResult> GetUser(Guid userId)
{
var user = await _usersService.GetUserAsync(userId);
if (user == null)
{
return BadRequest();
}
return Ok(user);
}
}
同样,这只是一个演示如何处理此问题的示例,通常您会以更一致的方式进行输入验证。
我正在尝试为一个 API 项目实施 .NET Core 3 app.UseExceptionHandler,但是每个 API 控制器都有一个通用记录器,我想将其传递给错误方法。例如,如果错误发生在我的 WorkingController 中,我希望 ILogger<WorkingController>
成为日志记录实体。我发现使用内置的 ExceptionHandler,我丢失了一些请求的上下文,如果可能的话我想捕获这个上下文。
这是我所有的 API 方法以前的样子:
[Route("api/working")]
[ApiController]
public class WorkingController
{
private readonly ILogger<WorkingController> _logger;
public WorkingController(ILogger<WorkingController> logger)
{
_logger = logger;
}
[Route("workingRoute")]
public IActionResult SomeMethod()
{
_logger.LogInformation("Starting SomeMethod");
try
{
// doing some stuff here
}
catch(Exception ex)
{
_logger.LogError(ex, "Something happened");
return Problem();
}
return Ok();
}
}
我尝试设置一个 BaseErrorController,其他控制器可以从中继承:
[ApiController]
public abstract class BaseErrorController<T> : ControllerBase
{
protected readonly ILogger<T> Logger;
public BaseErrorController(ILogger<T> logger)
{
Logger = logger;
}
[AllowAnonymous]
[Route("/error")]
public IActionResult Error()
{
var context = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
if (context != null)
{
var ex = context.Error;
Logger.LogError(ex, $"{context.Path} failed - {ex.Message}");
return Problem(
detail: context.Error.StackTrace,
title: context.Error.Message);
}
return Problem();
}
}
现在我以前的 WorkingController 看起来像这样,可以说它更干净(代码更少):
[Route("api/working")]
[ApiController]
public class WorkingController : BaseErrorController<WorkingController>
{
public WorkingController(ILogger<WorkingController> logger) : base(logger) { }
[Route("workingRoute")]
public IActionResult SomeMethod()
{
Logger.LogInformation("Starting SomeMethod");
// doing some stuff here
return Ok();
}
}
在 Startup.cs 中,我用 app.UseExceptionHandler("/error")
注册了这一切,它似乎工作正常。 . . except 现在在我的日志中,我看到以下错误(因为我有多个控制器实现了这个基本控制器):
An exception was thrown attempting to execute the error handler.
Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware
Microsoft.AspNetCore.Routing.Matching.AmbiguousMatchException: The request matched multiple endpoints.
Matches: Namespace.Controllers.WorkingController.Error (Namespace)
Namespace.Controllers.AnotherController.Error (Namespace)
at Microsoft.AspNetCore.Routing.Matching.DefaultEndpointSelector.ReportAmbiguity(CandidateState[] candidateState)
at Microsoft.AspNetCore.Routing.Matching.DefaultEndpointSelector.ProcessFinalCandidates(HttpContext httpContext, CandidateState[] candidateState)
at Microsoft.AspNetCore.Routing.Matching.DefaultEndpointSelector.Select(HttpContext httpContext, CandidateState[] candidateState)
at Microsoft.AspNetCore.Routing.Matching.DfaMatcher.MatchAsync(HttpContext httpContext)
at Microsoft.AspNetCore.Routing.Matching.DataSourceDependentMatcher.MatchAsync(HttpContext httpContext)
at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.HandleException(HttpContext context, ExceptionDispatchInfo edi)
有人知道这里的解决方案是什么吗? ExceptionHandler 是否存在过载,这可能正是我正在寻找的?这个解决方案是不是太精品了,我应该回到我之前做的事情?帮助我,Stack Overflow。谢谢!
不幸的是,根本没有 built-in 方法可以干净利落地做到这一点。你可以在这里找到一个包来帮助(我没看过),或者你可能想要 re-write ASP.NET 核心的某些部分,但我真的不想那样做。
还有另一种方法,根据您更喜欢哪个版本,recommended/recommended 反对,但我赞成前者。我没有在控制器级别出现 throwing/catching 异常,而是将控制器视为最愚蠢的东西,所以它们只是调用一些服务,仅此而已。
如果您想知道在何处引发了异常,或者您特别希望异常未被捕获,我的团队遵循的策略是创建自定义异常。然后您可以不捕获这些(并且 HTTP500 将返回给调用者)或者您可以有一个自定义中间件并在那里定义应该发生什么。
以下是一个示例,完全写在这里,因此可能需要进行一些更改,它只是为了演示一种可能的方法,而不是一个工作演示。
给定一些对您的域有效的例外情况:
public class UserNotFoundException : Exception { public Guid UserId { get; set; } }
public class InvalidModelException : Exception { }
还有一个异常处理程序:
public class MyCustomExceptionHandlerMiddleware
{
private readonly ILogger<MyCustomExceptionHandlerMiddleware> _logger;
public MyCustomExceptionHandlerMiddleware(ILogger<MyCustomExceptionHandlerMiddleware> logger)
{
_logger = logger;
}
public async Task Invoke(RequestDelegate next)
{
try
{
await next(); // without this, the request doesn't execute any further
}
catch (UserNotFoundException userNotFound)
{
_logger.LogError(userNotFound, "The user was not found");
// manipulate the response here, possibly return HTTP404
}
catch (Exception ex)
{
_logger.LogError(ex, "Something really bad happened");
// manipulate the response here
}
}
}
你可以有这样的东西:
public class UsersService : IUsersService
{
private readonly ILogger<UsersService> _logger;
private readonly UsersContext _context;
// assume UsersContext is an EntityFramework context or some database service
public UsersService(ILogger<UsersService> logger, UsersContext context)
{
_logger = logger;
_context = context;
}
public async Task<User> GetUserAsync(Guid userId)
{
try
{
if (userId == Guid.Empty)
{
throw new InvalidModelException();
}
var user = await _context.FindUserAsync(userId);
if (user == null)
{
throw new UserNotFoundException(userId);
}
return user;
}
catch (InvalidModelException invalidModel)
{
_logger.LogWarning("The received user id is empty");
return null;
}
}
}
及其对应的控制器:
public class UsersController : ControllerBase
{
private readonly IUsersService _usersService;
public UsersController(IUsersService usersService)
{
_usersService = usersService;
}
[HttpGet("userId:guid")]
public async Task<IActionResult> GetUser(Guid userId)
{
var user = await _usersService.GetUserAsync(userId);
if (user == null)
{
return BadRequest();
}
return Ok(user);
}
}
同样,这只是一个演示如何处理此问题的示例,通常您会以更一致的方式进行输入验证。