简体   繁体   English

Web API2,如何返回错误

[英]Web API2 ,How to return an error

public IHttpActionResult Save(item)
{
    try
    {
        result = MyRepository.Save(item);
        return Ok(result);
    }
    catch
    {
        // What should I do here?
        // I wish to return an error response how can i do that? 
    }
}

If it has no exception,I can return Ok.如果没有异常,我可以返回 Ok。

But if there is an exception what should I do?但如果出现异常,我该怎么办?

Note that I have javascript client请注意,我有 javascript 客户端

Create a model to hold what error information you want to return and pass that.创建一个模型来保存您想要返回并传递的错误信息。

public IHttpActionResult Save(item) {
    try {
        result = MyRepository.Save(item);
        return Ok(result);
    } catch {
        // What should I do here? Create a model to hold the data you want to return
        var myErrorModel = new {
            code = "My custom error code or 500 server error code",
            message = "some friendly error message"
        };

        // I wish to return an error response how can i do that?
        var response = Request.CreateResponse(HttpStatusCode.InternalServerError, myErrorModel);
        return ResponseMessage(response);
    }
}

In your javascript client in the error handler you can then access the model properties and handle the error as you see fit.在错误处理程序中的 javascript 客户端中,您可以访问模型属性并按照您认为合适的方式处理错误。

var handleResponse = function (data) {
    var code = data.code;
    var message = data.message
};

UPDATE:更新:

Agreeing with @Win, I personally don't like doing this in the controller actions as it is a Cross-cutting concern and have basically moved everything from within the catch block into a global error handler.同意@Win,我个人不喜欢在控制器操作中这样做,因为它是一个横切关注点,并且基本上已将所有内容从 catch 块内移到全局错误处理程序中。

In Web API 2, you can use BadRequest to return an error message.在 Web API 2 中,您可以使用BadRequest返回错误消息。

public IHttpActionResult Save(item)
{
    try
    {
        result = MyRepository.Save(item);
        return Ok(result);
    }
    catch
    {
        return BadRequest("Error message");
    }
}

FYI: Do not use try catch block just to swallow an exception.仅供参考:不要使用try catch 块来吞下异常。 I personally do not like using try catch block inside Action method.我个人不喜欢在 Action 方法中使用try catch块。 Instead, I let Web API 2 Global Exception Handler handles exceptions.相反,我让 Web API 2 Global Exception Handler 处理异常。 It is the out of the scope of your original question.这超出了您原始问题的范围。

You can use HttpResponseException to send an error message.您可以使用 HttpResponseException 发送错误消息。

public IHttpActionResult Save(item)
{
    try
    {
        result = MyRepository.Save(item);
        return Ok(result);
    }
    catch
    {
       var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
        {
            Content = new StringContent(string.Format("Error Message!!"),
            ReasonPhrase = "Error Reason phrase"
        };
        throw new HttpResponseException(resp);
 
    }
}

Use HttpResponseException as below:使用HttpResponseException如下:

throw new HttpResponseException(HttpStatusCode.InternalServerError)

Or another way is:或者另一种方式是:

var response = new HttpResponseMessage(HttpStatusCode.NotFound)  
    {  
        Content = new StringContent("some error"),  
            ReasonPhrase = "Not Found"  
    };  

    throw new HttpResponseException(response);

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

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