Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 654
Blake Rivell Avatar asked Oct 19 '22 19:10

Blake Rivell


2 Answers

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);
}
like image 125
Camilo Terevinto Avatar answered Nov 03 '22 21:11

Camilo Terevinto


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.

like image 43
Avi Avatar answered Nov 03 '22 20:11

Avi