Handling Web API 2.0 APIs
I am using Web API 2.0 to create my own project. My Api contains the ability to add, receive and order a product.
I want to handle the exception, but there are some issues that I confused a little.
I have a controller: ProdctController
with an action method AddProdct
.
[Route("~/CKService.svc/author/add")]
[HttpPost]
public IHttpActionResult AddProduct(ProductRequest request)
{
ProductManager.AddProduct(request.ProductId, request.ProductName,
request.Price);
return Ok(new AddProductResponse()
{
Status = AddProductStatus.Success
};)
}
Now if the product already exists, so the data access layer will throw DuplicateKeyException
I want to handle this excpetion and return a response like this:
return Ok(new AddProductResponse()
{
Status = AddProductStatus.AlreadyExists
};)
- Can you return
HTTP status code 200
? - How can I do this without adding
catch DuplicateKeyException
to my controller, because I think this is the wrong way.
thank
source to share
Here's one suggestion. (and I stress that this is just one of the many options available)
Refactor the manager to handle and return the product add status, and then return the appropriate status based response code to action.
[Route("~/CKService.svc/author/add")]
[HttpPost]
public IHttpActionResult AddProduct(ProductRequest request) {
var status = ProductManager.AddProduct(request.ProductId, request.ProductName, request.Price);
var response = new AddProductResponse() {
Status = status
};
if(status == AddProductStatus.Success) {
return Ok(response);
}
return BadRequest(response);
}
Avoid backtracking 200 OK
for requests that were not completed by default. This will lead to confusion in the client making the request.
source to share
HTTP 200 is not resonant - it indicates a successful request. Use the 4xx (Error) code instead. 409 (conflict) matches your situation of an existing object.
See: HTTP Response Code on Failure to Create POST Resources Due to Existing Comparable Resource
To catch the exception is ok. An unhandled exception will result in a 500 (internal server error) error that doesn't make sense in any way. Instead, you should catch the Exception and return an HTTP error like this ( ASP.NET Exception Handling ):
throw new HttpResponseException(
Request.CreateErrorResponse(HttpStatusCode.Conflict, message))
source to share