我有一个ASP.NET Core API调用第二个API。
如果第二个API出现错误,我会在服务层中抛出异常:
如何抛出一个异常,使得第二个 API 调用返回相同状态码的响应?
如果使用 HttpRequestException,即使 response 对象的 StatusCode 为 500,它也总是会返回 400。
编辑:第一个 API 端点如下:
第二个 API 终端的样子如下:
我尝试使用
我想保留原始有效负载中的
最终目标是将此返回:
如果第二个API出现错误,我会在服务层中抛出异常:
var response = await httpClient.SendAsync(request); //call second API
if (!response.IsSuccessStatusCode)
{
//return HTTP response with StatusCode = X, if response.StatusCode == X
throw new HttpRequestException(await response.Content.ReadAsStringAsync());
//this always returns 400
}
如何抛出一个异常,使得第二个 API 调用返回相同状态码的响应?
如果使用 HttpRequestException,即使 response 对象的 StatusCode 为 500,它也总是会返回 400。
编辑:第一个 API 端点如下:
public async Task<ActionResult<HttpResponseMessage>> CreateTenancy([FromBody]TenancyRequest tenancy)
{
//Make some calls...
return Created(string.Empty, new { TenancyID = newTenancyExternalId });
}
第二个 API 终端的样子如下:
[HttpPost]
public IHttpActionResult CreateTenancy([FromBody]TenancyDTO tenancyDTO)
{
var tenancy = GetTenancy();
return Created(string.Empty, tenancy);
}
我尝试使用
throw new HttpResponseException(response);
,但这会删除描述性异常消息,有效负载最终变成了这样:{
"Code": 500,
"CorrelationId": "2df08016-e5e3-434a-9136-6824495ed907",
"DateUtc": "2020-01-30T02:02:48.4428978Z",
"ErrorMessage": "Processing of the HTTP request resulted in an exception. Please see the HTTP response returned by the 'Response' property of this exception for details.",
"ErrorType": "InternalServerError"
}
我想保留原始有效负载中的
ErrorMessage
值:{
"Code": 400,
"CorrelationId": "ff9466b4-8c80-4dab-b5d7-9bba1355a567",
"DateUtc": "2020-01-30T03:05:13.2397543Z",
"ErrorMessage": "\"Specified cast is not valid.\"",
"ErrorType": "BadRequest"
}
最终目标是将此返回:
{
"Code": 500,
"CorrelationId": "ff9466b4-8c80-4dab-b5d7-9bba1355a567",
"DateUtc": "2020-01-30T03:05:13.2397543Z",
"ErrorMessage": "\"Specified cast is not valid.\"",
"ErrorType": "InternalServerError"
}
throw new HttpResponseException(response)
吗?即使用响应异常而不是请求异常? - Simply GedException
,例如ApiException
,它具有你关心的适当属性,包括一个StatusCode
属性,然后throw new ApiException(response.StatusCode)
。如果你有一个全局的异常处理程序/中间件,你可以在那里捕获异常并设置Response.StatusCode
。 - JohanP