6

Most of my functions involve a check to see if something exists. If it does not I return HttpNotFound(). They also involve a check to see if the parameters are correct. If they are not I return HttpBadRequest(). If everything is good I usually return an OK(dataGoesHere).

However what should I be doing when using a Try Catch block and an error is thrown. In the Catch I would like to simply return that there is a server error. I have seen some APIs actually return a custom message too.

It seems that in the ASP.NET 5 things are done a lot differently. I can't return BadRequest(), Conflict(), etc.. like in web api 2.

5
  • Usually exceptions are HTTP 500 Internal Server error Commented Dec 29, 2015 at 21:47
  • If you throw the exception instead of catching it, ASP.NET will automatically throw a 500 Commented Dec 29, 2015 at 21:47
  • So are you guys saying to just do 'throw e' in the catch? Commented Dec 29, 2015 at 21:50
  • 1
    I am just wondering what most Web APIs do in the case the core part of one of their function throws an unexpected error. What do they usually do to send the proper info to the client? At the very minimum its a 500 server error right? Commented Dec 29, 2015 at 21:51
  • 2
    Never do a throw e; of an exception you caught. Always just do throw;. See Is there a difference between “throw” and “throw ex”?. Commented Dec 29, 2015 at 21:59

3 Answers 3

2

This, modified to return InternalServerError, is what my team uses in a public application, where all non-approved requests are handled by this Controller:

public class ErrorController : ApiController
{
    [HttpGet, HttpPost, HttpPut, HttpDelete, HttpHead, HttpOptions, AcceptVerbs("PATCH")]
    public HttpResponseMessage HandleErrors()
    {
        HttpResponseMessage message = new HttpResponseMessage();
        message.Content = new StringContent("<html><body><div>This is a custom message that will be displayed to the user in HTML format</div></body></html>");
        message.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/html");
        message.StatusCode = HttpStatusCode.InternalServerError;
        return message;
    }
}

Apart from this, we use a custom DefaultHttpControllerSelector and a custom ApiControllerActionSelector where the request that ask for unknown controllers and actions are retrieved by the ErrorController.

EDIT: Adding another sample, this is how you could return a generic error message, supposing that the Action (function) you want to call returns a IHttpActionResult, and that you just want to return information on what happened:

return InternalServerError(ex);

Another sample, this is a little more complex than the previous one, but provides you with ways to send the details that you want, in the format you want:

public class SomethingFailedResult : IHttpActionResult
{
    private HttpControllerContext _Context { get; set; }
    private string _Message { get; set; }

    public SomethingFailedResult(HttpControllerContext context, string message)
    {
        _Context = context;
        _Message = message;
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        return Task.FromResult(_Context.Request.CreateResponse(HttpStatusCode.InternalServerError,
            _Message, "someMediaType"));
    }
}

You would then create a helper method in your Controller, like this:

private SomethingFailedResult SomethingFailed(string contents, HttpControllerContext context)
{
    return new ExpectionFailedResult(contents, context);
}
Sign up to request clarification or add additional context in comments.

2 Comments

To use HttpResponseMessage I think I need to add Microsoft.Net.Http to my project. I wonder why this isn't included in a default asp.net 5 web api app.
@BlakeRivell I don't remember right now whether it was included by default or not, made this some time ago. I added two more ways to do what you want
1

When unexpected error occurs, you should log the exception and send generic message to the user. You can attach a unique id to the error message that can be found later in the database by the admin or the developer.

2 Comments

In a Web API controller what function do I use to send a simple generic error message as a response?
1

if using WebAPI 2.0

use IHttpActionResult and Return InternalServerError as follows

public IHttpActionResult Get()
{
   return InternalServerError();
}

For WebAPI 1.0 use HttpResponse message as follows :-

return Request.CreateResponse(HttpStatusCode.InternalServerError);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.