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.

Blake Rivell
  • 13,105
  • 31
  • 115
  • 231
  • Usually exceptions are HTTP 500 Internal Server error – hyde Dec 29 '15 at 21:47
  • If you throw the exception instead of catching it, ASP.NET will automatically throw a 500 – Camilo Terevinto Dec 29 '15 at 21:47
  • So are you guys saying to just do 'throw e' in the catch? – Blake Rivell Dec 29 '15 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? – Blake Rivell Dec 29 '15 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”?](http://stackoverflow.com/questions/730250/is-there-a-difference-between-throw-and-throw-ex). – mason Dec 29 '15 at 21:59

3 Answers3

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);
}
Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
  • 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. – Blake Rivell Dec 29 '15 at 22:07
  • @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 – Camilo Terevinto Dec 29 '15 at 22:16
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.

Avi
  • 1,924
  • 3
  • 17
  • 31
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);
Learner
  • 1,277
  • 3
  • 15
  • 34