2
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.

But if there is an exception what should I do?

Note that I have javascript client

Nkosi
  • 235,767
  • 35
  • 427
  • 472
Kuttan Sujith
  • 7,889
  • 18
  • 64
  • 95
  • Possible duplicate of [Returning http status code from Web Api controller](http://stackoverflow.com/questions/10655350/returning-http-status-code-from-web-api-controller) – Igor Jun 16 '16 at 13:05
  • Or see [Return content with IHttpActionResult for non-OK response](http://stackoverflow.com/questions/28588652/return-content-with-ihttpactionresult-for-non-ok-response). You want to return a non 200 status code to the caller, that is the accepted way to return errors. – Igor Jun 16 '16 at 13:08

4 Answers4

1

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.

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.

Nkosi
  • 235,767
  • 35
  • 427
  • 472
1

In Web API 2, you can use BadRequest to return an error message.

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. I personally do not like using try catch block inside Action method. Instead, I let Web API 2 Global Exception Handler handles exceptions. It is the out of the scope of your original question.

Win
  • 61,100
  • 13
  • 102
  • 181
0

You can use HttpResponseException to send an error message.

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);
 
    }
}
0

Use HttpResponseException as below:

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);
Alireza Ahmadi
  • 8,579
  • 5
  • 15
  • 42