简体   繁体   English

如何返回带有详细错误消息的错误?

[英]How to return an error with detailed error message?

I use the following code in an ASP.NET Core project to return a detailed error message (business logic related errors): 我在ASP.NET Core项目中使用以下代码来返回详细的错误消息(与业务逻辑相关的错误):

public async Task<IEnumerable<PoolStatic>> Get(string id)
{
    if (id== null)
    {
        var resp = new HttpResponseMessage(HttpStatusCode.BadRequest)
        {
            Content = new StringContent("id is not provided."),
            ReasonPhrase = "id not found"
        };
        throw new HttpResponseException(resp);
    }
 ....

However, the client gets HTTP 500 and the raw response message doesn't contain the message I set: 但是,客户端获取HTTP 500 ,并且原始响应消息不包含我设置的消息:

HTTP/1.1 500 Internal Server Error
Date: Sat, 10 Dec 2016 02:19:09 GMT
Content-Length: 0
Server: Kestrel

In ASP.NET Core, a better way to achieve this behavior would be to return a Task<IActionResult> from the controller, which lets you do this: 在ASP.NET Core中,实现此行为的更好方法是从控制器返回Task<IActionResult> ,您可以通过这样做:

public async Task<IActionResult> Get(string id)
{
    if (id== null)
    {
        return BadRequest("id is not provided.");
    }

    // other code, including:
    // return Ok(some data);
}

BadRequest() is a helper method that creates a BadRequestObjectResult , and sends a 400 Bad Request response back to the client with whatever data you provide. BadRequest()是一个帮助程序方法,它创建BadRequestObjectResult ,并使用您提供的任何数据将400 Bad Request响应发送回客户端。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM