使用自定义响应处理 .NET5 中的错误 class

Handling error in .NET5 with a custom response class

我有 Java/Spring 背景,我正在尝试学习 .NET 5.I 在 Web 上工作 API,一切正常,但不知何故我无法理解或无法使其工作,我尝试了一些在线找到的解决方案,但随着多年来情况的变化,我不知道它们是否不再起作用或者是否有更好的方法来做到这一点。

基本上,我想在我的 .NET 中处理错误 API。

我的服务有这个代码:

public Users execute(int id)
{
    var foundUser = this.userRepository.findById(id);
    if (foundUser == null)
    {
        throw new HttpException(HttpStatusCode.NotFound, "User not found");
    }
    return foundUser;
}

HttpException 是我创建的自定义异常,因此我可以控制状态代码

using System;
using System.Net;

namespace dotnetex.shared.Errors
{
    public class HttpException : Exception
    {

        public HttpStatusCode Status { get; set; }

        public HttpException(HttpStatusCode status, string msg) : base(msg)
        {
            Status = status;
        }
    }
}

我的启动 class 有异常处理程序指向我的路线:

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseExceptionHandler("/error"); // Add this
[...]

我的路线是这样的

using System.Net;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;

namespace dotnetex.shared.Errors.Controller
{
    [ApiController]
    public class ErrorController : ControllerBase
    {
        [Route("/error")]
        public IActionResult Error()
        {
            var exception = HttpContext.Features.Get<IExceptionHandlerFeature>();
            HttpException error = (HttpException)exception.Error;
            var statusCode = (int)error.Status;
            return Problem(detail: error.Message, statusCode: statusCode);
        }
    }
}

出于某种原因,当我从“error”变量中获取 statusCode 时,我的响应中断了,我的 Insomnia 告诉我 Error: Transferred a partial file。调试显示 statusCode 变量已设置。当我通过代码设置一个数字时,一切正常。

我试过在 Insomnia、Postman、Chrome 浏览器、CURL 中调用端点。全部显示错误

最后,如果 possible.I 想从这条路线 return 自定义错误对象 API 错误而不是“问题”,就像这个:

namespace dotnetex.shared.Errors
{
    public class APIError
    {
        private int status_code = 500;
        private string message = "";
        public APIError(int status_code, string message)
        {
            this.status_code = status_code;
            this.message = message;
        }
    }
}

控制台中的异常是:

fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[1]
      An unhandled exception has occurred while executing the request.
      dotnetex.shared.Errors.HttpException: User not found
         at dotnetex.modules.users.Services.Implementations.GetUserByIdService.GetUserByIdService.execute(Int32 id) in /home/matt/Source/net/dotnetexSl/dotnetex/modules/users/Services/Implementations/GetUserByIdService/GetUserByIdService.cs:line 23
         at modules.users.Services.UserServices.GetUserById(Int32 id) in /home/matt/Source/net/dotnetexSl/dotnetex/modules/users/Services/UserServices.cs:line 45
         at modules.users.Controllers.UsersControllers.getSingleUser(Int32 id) in /home/matt/Source/net/dotnetexSl/dotnetex/modules/users/Controllers/UsersControllers.cs:line 53
         at lambda_method1(Closure , Object , Object[] )
         at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
      --- End of stack trace from previous location ---
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
      --- End of stack trace from previous location ---
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
         at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
         at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
         at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)
warn: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[4]
      No exception handler was found, rethrowing original exception.
fail: Microsoft.AspNetCore.Server.Kestrel[13]
      Connection id "0HM6S5CSRT4C8", Request id "0HM6S5CSRT4C8:00000002": An unhandled exception was thrown by the application.
      dotnetex.shared.Errors.HttpException: User not found
         at dotnetex.modules.users.Services.Implementations.GetUserByIdService.GetUserByIdService.execute(Int32 id) in /home/matt/Source/net/dotnetexSl/dotnetex/modules/users/Services/Implementations/GetUserByIdService/GetUserByIdService.cs:line 23
         at modules.users.Services.UserServices.GetUserById(Int32 id) in /home/matt/Source/net/dotnetexSl/dotnetex/modules/users/Services/UserServices.cs:line 45
         at modules.users.Controllers.UsersControllers.getSingleUser(Int32 id) in /home/matt/Source/net/dotnetexSl/dotnetex/modules/users/Controllers/UsersControllers.cs:line 53
         at lambda_method1(Closure , Object , Object[] )
         at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
      --- End of stack trace from previous location ---
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
      --- End of stack trace from previous location ---
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
         at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
         at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
         at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)
         at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.HandleException(HttpContext context, ExceptionDispatchInfo edi)
         at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)
         at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)

所以如果你能帮我找到解决办法,我将不胜感激。

提前致谢!

我不太确定你在这里问什么。如果您使用错误控制器并抛出自定义异常,我会检查您的控制器上的异常类型。

因此,例如,如果您定义一个自定义 HttpException,然后像 Throw new HttpException(HttpStatusCodes.NotFound, "Woah something happened!); 那样抛出该异常,那么它会被您的错误控制器捕获。

默认情况下,您捕获的普通 Exception 不会有 status 属性,因此您需要像这样处理它:

[Route("error")]
public ErrorResponseModel Error()
{
    var context = HttpContext.Features.Get<IExceptionHandlerFeature>();
    var exception = context.Error;

    // Handle if the exception is a HttpException
    if(exception is HttpException httpException)
    {
         Response.StatusCode = (int)httpException.status;

         return new ErrorResponseModel(httpException);
    }

    // Handle all other exceptions
    Response.StatusCode = (int)HttpStatusCode.InternalServerError;

    return new ErrorResponseModel(exception);
}

您可以看到,我没有返回 IActionResult,而是简单地定义了我自己的错误模型,然后将 Response.StatusCode 设置为我想要的任何值。

这应该可以帮助您入门。

ASP.NET Core 5 介绍 breaking-change in handling the response status code NotFound 404. Use ExceptionHandlerOptions.AllowStatusCode404Response 属性.

像这样修复 UseExceptionHandler 方法:

Startup.cs

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
 {
    app.UseExceptionHandler(
          new ExceptionHandlerOptions()
          {
              AllowStatusCode404Response = true, // important!
              ExceptionHandlingPath = "/error"                  
          }
      );      
  }