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

如何解决使用自定义响应类处理 .NET5 中的错误

我来自 Java/Spring 背景,我正在尝试学习 .NET 5。我正在研究 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;
        }
    }
}

我的启动类有指向我的路由的异常处理程序:

    // 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);
        }
    }
}

出于某种原因,当我从“错误”变量中获取 statusCode 时,我的响应被破坏了,我的 Insomnia 告诉我 Error: Transferred a partial file。调试显示我设置了 statusCode 变量。当我通过代码设置一个数字时,事情会按预期工作。

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

最后,如果可能的话。我想从这个路由返回一个名为 API Error 的自定义错误对象,而不是“问题”,就像这个:

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,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,Task task)
         at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.HandleException(HttpContext context,ExceptionDispatchInfo edi)
         at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware,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 在处理响应状态代码 NotFound 404 时引入了 breaking-change。使用 ExceptionHandlerOptions.AllowStatusCode404Response 属性。

像这样修复 UseExceptionHandler 方法:

Startup.cs

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res