asp.netodataasp.net-web-api2dataserviceodata-v4

How to handle exceptions in Odata V4 client?


Asp.Net Web API Odata Controller Action:

public async Task<IHttpActionResult> Post(Product product)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }
    db.Products.Add(product);
    await db.SaveChangesAsync();
    return Created(product);
}

Odata client code: (Odata v4 client code generator v4)

static void AddProduct(Default.Container container, ProductService.Models.Product product)
{
    container.AddToProducts(product);
    var serviceResponse = container.SaveChanges();
    foreach (var operationResponse in serviceResponse)
    {
        Console.WriteLine("Response: {0}", operationResponse.StatusCode);
    }
}

I would like to handle exception in a proper way inside AddProducts() Method while saving the changes.

How can I catch process the ModelState error which is sent from server return BadRequest(ModelState);?

Finally I just want to show the error message to the end uses which was sent from server. Example: "Product category is required."

What is the use of ODataException class? Will this help me?

Please help me.


Solution

  • if I understood well, you want to intercept that the ModelState is not valid, and customize the OData error that is shown to the user.

    If you just want that the errors of the invalid model show up in the returned payload, you can use:

    if (!ModelState.IsValid)
    {
        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
    }
    

    If you want to fully control the exceptions handling and messages shown, I'd suggest several action points for you to accomplish this:

    You can find more information about all of this in here. In the end, the error and exception handling is the same for ASP.Net Web API, with or without OData; difference is that if you have an OData API, you should return errors in OData style.

    Hope all this info is understandable and helps you somehow.