Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web API 2.0 Exception Handling

I am using Web API 2.0 to create my own project. My Api contain ability to Add , Get and book product.

I Want to handle exception but there is some issue I little bit confused.

I have a controller: ProdctController with 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 response like this:

  return Ok(new AddProductResponse()
    {
        Status = AddProductStatus.AlreadyExists
    };)
  1. Is this reasonable to return HTTP status code 200?
  2. How can I do this without add catch DuplicateKeyException to my controller because i think this is not the right way.

Thanks

like image 242
maz Avatar asked Jan 30 '26 14:01

maz


1 Answers

Here is one suggestion. (and I emphasis that it is just one of the many options you have available)

Refactor the manager to handle and return the status of adding the product and then have the action return the appropriate response code based on the status.

[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 return 200 OK for requests that have not completed as intended. That will mislead the client making the request.

like image 133
Nkosi Avatar answered Feb 02 '26 03:02

Nkosi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!