locked
Exceptions in Core async project RRS feed

  • Question

  • User791773689 posted

    Hello everybody,

    I write WebAPI projects with Microsoft.EntityFrameworkCore.

    Data goes through an Interface, a Repository, and a Controller.

    I have got the habit to put a try ... catch in the repository, if I remember correctly I saw that this way in the documentation.

    But suddenly I am wondering ...

    Probably that is not a good idea, for that way I have the same result for an error or a non existing record.

    Maybe it would be better that the repository throws an exception to the controller, which then has the possibility to distinguish between NotFound and BadRequest.

    Am I pushing an open door ?

    Saturday, August 3, 2019 8:28 AM

All replies

  • User-719153870 posted

    Hi Gluups,

    Probably that is not a good idea, for that way I have the same result for an error or a non existing record.

    This is strange cause NotFound and BadRequest should show the different exceptions messages.

    Can you share us your code in which NotFound and BadRequest give you the same result?

    Best Regard,

    Yang Shen

    Monday, August 5, 2019 5:15 AM
  • User-2054057000 posted

    Probably that is not a good idea, for that way I have the same result for an error or a non existing record.

    Yes you should provide specific error messages to the client in your API. For non-existing records you can simply return Status400BadRequest like this:

    return StatusCode(StatusCodes.Status400BadRequest);

    Refer this tutorial for all the details: 

    Returning BadRequest (400), Unauthorized (401), NotFound (404) status codes from Action

    Monday, August 5, 2019 5:02 PM
  • User791773689 posted

    Yes, that can still refine the result.

    But of course, if I put a try...catch in the Repository, it will return 0, and the controller returns Ok(0), no ?

    Monday, August 5, 2019 6:19 PM
  • User-2054057000 posted

    Yes, that can still refine the result.

    But of course, if I put a try...catch in the Repository, it will return 0, and the controller returns Ok(0), no ?

    Thats why you need to apply the if else logic and return different HTTP values. Check my link already given in the above post.

    Tuesday, August 6, 2019 5:13 AM
  • User791773689 posted

    Different integer (or string) values from the repository, and different status values from the controller.

    Tuesday, August 6, 2019 5:28 AM