Reputation: 53
I'm creating a REST Web API in C# using ASP.NET Web API for MVC 5.
I've created an abstract class BaseApiController
, which all API controllers extend. In this base controller I handle all the Exceptions and everything the controllers need to properly work.
I've already implemented exception handling for the following Exceptions:
public override async Task<HttpResponseMessage> ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)
{
string controllerName = null;
string actionName = null;
try
{
SetContext(controllerContext);
SetServices();
await AuthenticateUser();
controllerName = controllerContext?.Controller?.GetType().FullName;
var services = controllerContext?.ControllerDescriptor?.Configuration?.Services;
actionName = services?.GetActionSelector()?.SelectAction(controllerContext)?.ActionName;
return await base.ExecuteAsync(controllerContext, cancellationToken);
}
catch (HttpResponseException e)
{
ClientDataService.Logger(e, $"{controllerName}.{actionName}",
$"Response -> Status Code: {(int)e.Response.StatusCode}, Reason: {e.Response.ReasonPhrase}",
SystemLogOriginTypesEnum.WEBSITE_API);
throw;
}
catch (Exception e)
{
ClientDataService.Logger(e, $"{controllerName}.{actionName}",
$"Response -> Status Code: {(int)HttpStatusCode.InternalServerError}, Reason: Internal server error",
SystemLogOriginTypesEnum.WEBSITE_API);
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent("Internal server error"),
ReasonPhrase = "Internal server error"
});
}
The Controllers throw HttpResponseException
mainly when mandatory parameters aren't passed or properly setup (HTTP status code
400), the second is when something went terribly wrong (HTTP status code 500).
My question is what kind of HTTP status code should the API respond when a service throws exceptions like a NotSupportedException
or a custom InvalidSortAttributeException
?
I don't mean HTTP status categories, i.e., 4XX vs 5XX, since the InvalidSortAttributeException
should be a 4XX category because the error gets thrown from an invalid request, maybe a 400 (Bad Request)!?
Although the second, I believe could fall on both categories since the server doesn't support the request but it doesn't exactly mean it will not support it in the future, maybe a 406 (NotAcceptable) or a 501 (NotImplemented)?
Upvotes: 1
Views: 3534
Reputation: 5103
The 4XX is built specifically for user errors The 5XX is built for internal server errors
You have to respond with an intelligent code for the scenario. If there is a notsupported exception but your code caller constructed a not supported scenario, then it's 500. If the user managed to put together a bad request, it should be 4XX.
Note also that there's a difference between missing an attribute in the JSON request (400) and missing a value in the url (404) or the resource is no longer available (404).
Upvotes: 1