Returning a 500 internal server error when code errors in asp.net 5 web api

19,658

Solution 1

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

Solution 2

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.

Solution 3

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);
Share:
19,658
Blake Rivell
Author by

Blake Rivell

I am a .NET developer who builds custom web applications for businesses. I have a very strong passion for what I do. My hobbies are video games and fitness.

Updated on June 12, 2022

Comments

  • Blake Rivell
    Blake Rivell almost 2 years

    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.