0

I am building a REST API using .net WEB API.

What is the best/recommended response for expected errors?

Situation: There is plane with places.The place can be booked by another person. If reservation was failed by expected error, what the response I need to create ? Now, I use this:

[Route("{number}/reservation"), HttpPost]
public IHttpActionResult Reservation(string number)
{           
  if (string.IsNullOrEmpty(number))
    return Content(HttpStatusCode.BadRequest, "Number required");

  var result = Reservation(number);
  if (result.IsValid)
  {
     return Request.CreateResponse(HttpStatusCode.OK);
  }
  else
     return Request.CreateResponse(HttpStatusCode.OK,result.ErrorMessage);
}

1 Answers1

0

The way you are generating error responses from your API seems fine, but best practice would bring in using ExceptionFilters in your application which helps you globally handle both(Handled & Unhandled) exceptions.

You can simply create an ExceptionFilter in your application like this -

public class MyExceptionFilterAttribute : ExceptionFilterAttribute 
    {
        public override void OnException(HttpActionExecutedContext context)
        {
            if (context.Exception is NotImplementedException)
            {
                context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented);
            }
            // Other checks can be added
        }
    }

And then registering your filter in your API in the

WebApiConfig.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Filters.Add(new MyExceptionFilterAttribute());
    }
}

Through this, anytime unhandled Exception will be thrown from your API filter will generate the response using OnException method of the Filter.

Ipsit Gaur
  • 2,872
  • 1
  • 23
  • 38