gdubs
gdubs

Reputation: 2754

.NET web API exception error details

I'm really new to web APIs and was experimenting on some API controllers exceptions. My problem here is when an exception is thrown, the application will return too much information which would include the stacktrace and some properties of the model being returned. I was wondering if the exceptions returned can be limited to just a message?

Here's an example:

public IEnumerable<Appointments> GetAll(int id)
{
    IEnumerable<Appointments> appointments = icdb.Appointments.Where(m => m.Id== id).AsEnumerable();
    return appointments;
}

And if this would return an exception (diff issue), it would return something like this:

{"Message":"An error has occurred.","ExceptionMessage":"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.","ExceptionType":"System.InvalidOperationException","StackTrace":null,"InnerException":{"Message":"An error has occurred.","ExceptionMessage":"Self referencing loop detected for property 'UpdateBy' with type 'System.Data.Entity.DynamicProxies.User_B23589FF57A33929EC37BAD9B6F0A5845239E9CDCEEEA24AECD060E17FB7F44C'. Path '[0].UpdateBy.UserProfile.UpdateBy.UserProfile'.","ExceptionType":"Newtonsoft.Json.JsonSerializationException","StackTrace":.................................. : : : }

As you noticed, it would return a stacktrace with most of the properties of my model. Is there a way where I can just return a message when an exception is thrown?

Upvotes: 2

Views: 2837

Answers (1)

von v.
von v.

Reputation: 17118

You mentioned you have an API controller. If you encounter an error, you should do this:

// A handled exception has occurred so return an HTTP status code
return Request.CreateResponse<string>(HttpStatusCode.BadRequest, your_message);

So for your given sample code you can have something like this:

public IEnumerable<Appointments> GetAll(int id)
{
    IEnumerable<Appointments> appointments= null;
    try {
        icdb.Appointments.Where(m => m.Id== id).AsEnumerable();
    }
    catch {
        var message = new HttpResponseMessage(HttpStatusCode.BadRequest);
        message.Content = new StringContent("some custom message you want to return");
        throw new HttpResponseException(message);
    }
    return appointments;
}

If your controller encounters an unhandled exception the calling code will receive a 500 status.

Upvotes: 2

Related Questions