gpt4 book ai didi

c# - 如何从 WebAPI 中的异常获取 HttpStatusCode?

转载 作者:行者123 更新时间:2023-11-30 15:32:15 25 4
gpt4 key购买 nike

无论如何我们可以在异常捕获时获取 HttpStatus 代码吗?异常可能是 Bad Request408 Request Timeout419 Authentication Timeout?如何在异常 block 中处理?

 catch (Exception exception)
{
techDisciplines = new TechDisciplines { Status = "Error", Error = exception.Message };
return this.Request.CreateResponse<TechDisciplines>(
HttpStatusCode.BadRequest, techDisciplines);
}

最佳答案

我注意到您正在捕获一个通用异常。您需要捕获更具体的异常才能获得其独特的属性。在这种情况下,请 try catch HttpException 并检查其状态代码属性。

但是,如果您正在编写服务,则可能需要使用 Request.CreateResponse 来报告错误情况。 http://www.asp.net/web-api/overview/web-api-routing-and-actions/exception-handling有更多信息

关于c# - 如何从 WebAPI 中的异常获取 HttpStatusCode?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19364554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com