如何返回一个完整的BadRequest响应体,包含自定义的错误信息。

huangapple go评论66阅读模式
英文:

How to return a full BadRequest response body with my own error

问题

Good day

我是新手对API的理解。 我已经使用过它们,但直到现在才不得不发布自己的API。

我想要在所有错误响应中保持统一性。 除了200范围之外的所有响应都应该与默认错误响应看起来一样,但当我添加自己的错误时,Postman中只返回我的错误。

说明:

例如,当未传递所需参数时,会有一个自动默认的响应体,看起来像这样:

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "00-118adfb731bbdb32e865873f70487da2-f5994dea1e69866a-00",
    "errors": {
        "Spec": [
            "The Spec field is required."
        ]
    }
}

请注意,我没有验证字段,也没有生成上述错误消息。

当我返回BadRequest()响应时,在Postman中我看到一个响应体,其中还包含类型、状态、标题和traceId:

API:

public async Task<IActionResult> GetList([FromQuery] SearchCriteria criteria)
{ 
    return BadRequest();  
}

响应:

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "Bad Request",
    "status": 400,
    "traceId": 
}

但是,当我添加错误消息时,Postman中只返回我的错误消息:

API:

public async Task<IActionResult> GetList([FromQuery] SearchCriteria criteria)
{ 
    return BadRequest(error: new { error = "Unable to return list" });  
}

响应:

{
    "error": "Unable to return list"
}

我如何添加自己的错误消息,同时仍然在响应中包含类型、标题、状态和traceId,以便用户始终知道可以期望什么?

非常感谢。

英文:

Good day

I am new to API's. I have consumed them, but never had to published my own until now.

I would like to have uniformity in all error responses. I would like to have all my responses (other than 200 range) look the same as the default error response, but when I add my own error, then only my error is returned in Postman.

Illustration:

When a required parameter is not passed for example, there is an auto default response body which look like this:

{
    &quot;type&quot;: &quot;https://tools.ietf.org/html/rfc7231#section-6.5.1&quot;,
    &quot;title&quot;: &quot;One or more validation errors occurred.&quot;,
    &quot;status&quot;: 400,
    &quot;traceId&quot;: &quot;00-118adfb731bbdb32e865873f70487da2-f5994dea1e69866a-00&quot;,
    &quot;errors&quot;: {
        &quot;Spec&quot;: [
            &quot;The Spec field is required.&quot;
        ]
    }
}

Note that I am not validating fields and I did not generate the above error message.

When I return a BadRequest() response, in Postman I see a response body also containing the type, status, title and traceId:

API:

public async Task&lt;ActionResult&gt; GetList([FromQuery] SearchCriteria criteria)
{ 
    return BadRequest();  
}

Response:

{
    &quot;type&quot;: &quot;https://tools.ietf.org/html/rfc7231#section-6.5.1&quot;,
    &quot;title&quot;: &quot;Bad Request&quot;,
    &quot;status&quot;: 400,
    &quot;traceId&quot;: 
}

BUT when I add an error message, then only my error message is returned in Postman:

API:

public async Task&lt;ActionResult&gt; GetList([FromQuery] SearchCriteria criteria)
{ 
    return BadRequest(error: new { error = &quot;Unable to return list&quot; });  
}

Response:

{
    &quot;error&quot;: &quot;Unable to return list&quot;
}

How can I add my own error message and also still have the type, title, status, and traceId in the response so the user always knows what to expect?

Thank you in advance.

答案1

得分: 2

The translated code part:

可能最简单的方法是使用 `ValidationProblem`:

ModelState.AddModelError("return", "无法返回列表");
return ValidationProblem(ModelState);

And the JSON response:

{
   "type":"https://tools.ietf.org/html/rfc7231#section-6.5.1",
   "title":"发生一个或多个验证错误。",
   "status":400,
   "traceId":"00-4091c0b6419e8cc5d4e9cb1da3764f11-d2bc593ce1a51e0a-00",
   "errors":{
      "return":[
         "无法返回列表"
      ]
   }
}

The link remains the same.

英文:

Probably easiest approach would be using ValidationProblem:

ModelState.AddModelError(&quot;return&quot;, &quot;Unable to return List&quot;);
return ValidationProblem(ModelState);

Which produces the following response for me:

{
   &quot;type&quot;:&quot;https://tools.ietf.org/html/rfc7231#section-6.5.1&quot;,
   &quot;title&quot;:&quot;One or more validation errors occurred.&quot;,
   &quot;status&quot;:400,
   &quot;traceId&quot;:&quot;00-4091c0b6419e8cc5d4e9cb1da3764f11-d2bc593ce1a51e0a-00&quot;,
   &quot;errors&quot;:{
      &quot;return&quot;:[
         &quot;Unable to return List&quot;
      ]
   }
}

Otherwise you might need to dabble with methods exposed by ProblemDetailsFactory.

答案2

得分: 0

JsonResult应返回一个自定义类

JsonResult具有一个可设置的StatusCode属性

// 返回到客户端的模型
private class ReturnModel
{
    public string? message { get; set; }
    ...
}

// 在控制器方法中
return new JsonResult(new ReturnModel
{
    message = "..."
})
{
    StatusCode = (int)HttpStatusCode.BadRequest
};
英文:

You should return a JsonResult with a custom class

JsonResult has a StatusCode property you can set

// model to return to client side
private class ReturnModel
{
    public string? message { get; set; }
    ...
}

// in controller method
return new JsonResult(new ReturnModel
{
    message = &quot;...&quot;
})
{
    StatusCode = (int)HttpStatusCode.BadRequest
}; 

huangapple
  • 本文由 发表于 2023年4月13日 23:36:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76007318.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定