作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试使用自定义错误处理程序为我的 .NET Core 3 API 返回格式正确的异常。处理程序运行良好,我遇到的问题是编写适当的单元测试来测试处理程序。我为此注册了中间件,如下所示:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IEnvService envService)
{
if (envService.IsNonProductionEnv())
{
app.UseExceptionHandler("/Error-descriptive");
}
else
{
app.UseExceptionHandler("/Error");
}
...
}
public IActionResult ErrorDescriptive()
{
if (!_env.IsNonProductionEnv())
throw new InvalidOperationException("This endpoint cannot be invoked in a production environment.");
IExceptionHandlerFeature exFeature = HttpContext.Features.Get<IExceptionHandlerFeature>();
return Problem(detail: exFeature.Error.StackTrace, title: exFeature.Error.Message);
}
IExceptionHandlerFeature exFeature = HttpContext.Features.Get<IExceptionHandlerFeature>();
最佳答案
您可以通过注入(inject) IHttpContextAccessor
来实现这一点。 Controller 中的界面。
这个接口(interface)提供了一个抽象来访问 HttpContext 对象,主要是在你的 web 库之外。
要使用它,您必须services.AddHttpContextAccessor();
在您的启动文件中。
然后你可以将它注入(inject)你的 Controller 。
[ApiController]
public class ErrorController
{
private readonly ILogger<ErrorController> logger;
private readonly IHttpContextAccessor httpContextAccessor;
public ErrorController(ILogger<ErrorController> logger, IHttpContextAccessor httpContextAccessor){
this.logger = logger;
this.httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor));
}
}
[Route("/error-development")]
public IActionResult HandleErrorDevelopment()
{
var exceptionFeature = this.httpContextAccessor.HttpContext.Features.Get<IExceptionHandlerFeature>();
var error = exceptionFeature.Error;
}
public ErrorControllerTests() {
this.httpContextAccessorMock = new Mock<IHttpContextAccessor>();
this.httpContextMock = new Mock<HttpContext>();
this.featureCollectionMock = new Mock<IFeatureCollection>();
this.exceptionHandlerFeatureMock = new Mock<IExceptionHandlerFeature>();
this.httpContextAccessorMock.Setup(ca => ca.HttpContext).Returns(this.httpContextMock.Object);
this.httpContextMock.Setup(c => c.Features).Returns(this.featureCollectionMock.Object);
this.featureCollectionMock.Setup(fc => fc.Get<IExceptionHandlerFeature>()).Returns(this.exceptionHandlerFeatureMock.Object);
this.controller = new ErrorController(null, this.httpContextAccessorMock.Object);
}
[Fact]
public void HandleErrorDevelopment() {
Exception thrownException;
try{
throw new ApplicationException("A thrown application exception");
}
catch(Exception ex){
thrownException = ex;
}
this.exceptionHandlerFeatureMock.Setup(ehf => ehf.Error).Returns(thrownException);
var result = this.controller.HandleErrorDevelopment();
var objectResult = result as ObjectResult;
Assert.NotNull(objectResult);
Assert.Equal(500, objectResult.StatusCode);
var problem = objectResult.Value as ProblemDetails;
Assert.NotNull(problem);
Assert.Equal(thrownException.Message, problem.Title);
Assert.Equal(thrownException.StackTrace, problem.Detail);
}
ControllerBase.Problem()
方法。此实现依赖于
ControllerBase.HttpContext
检索
ProblemDetailsFactory
目的。
NullReferenceException
.
ProblemDetails
的 helper 目的。您再次可以看到
Default implementation on GitHub .
private ProblemDetails CreateProblemDetails(
int? statusCode = null,
string title = null,
string type = null,
string detail = null,
string instance = null){
statusCode ??= 500;
var problemDetails = new ProblemDetails
{
Status = statusCode.Value,
Title = title,
Type = type,
Detail = detail,
Instance = instance,
};
var traceId = Activity.Current?.Id ?? this.httpContextAccessor.HttpContext?.TraceIdentifier;
if (traceId != null)
{
problemDetails.Extensions["traceId"] = traceId;
}
return problemDetails;
}
[Route("/error-development")]
public IActionResult HandleErrorDevelopment() {
var exceptionFeature = this.httpContextAccessor.HttpContext.Features.Get<IExceptionHandlerFeature>();
var error = exceptionFeature.Error;
this.logger?.LogError(error, "Unhandled exception");
var problem = this.CreateProblemDetails(title: error.Message, detail: error.StackTrace);
return new ObjectResult(problem){
StatusCode = problem.Status
};
}
if (error is HandledApplicationException)
{
// handled exceptions with user-friendly message.
problem = this.CreateProblemDetails(title: error.Message);
}
else {
// unhandled exceptions. Provice a generic error message to display to the end user.
problem = this.CreateProblemDetails(title: "An unexpected exception occured. Please try again or contact IT support.");
}
关于c# - 如何对异常处理程序中间件进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60288329/
我是一名优秀的程序员,十分优秀!