1

I have the below method in my controller that calls CreateProductCommand:

    public async Task<ActionResult> Create([FromBody] CreateProductCommand createProductCommand)
    {
        var userId = await Mediator.Send(createProductCommand);

        if (userId != Guid.Empty)
        {
            return Ok();
        }
        return BadRequest(); // I want command error to be displayed here
    }

My CreateProductCommand has the below:

    public async Task<Guid> Handle(CreateProductCommand request, CancellationToken cancellationToken)
    {
        // check database to see if product exists
         if(productExists)
          {
            throw Exception("Product Already Exists");
          }
     }

Is there a way to make that [ throw Exception("Product Already Exists")] be returned to the controller? At the moment the application crashes at the throw Exception line.

Thanks in advance.

avdeveloper
  • 449
  • 6
  • 30
  • Does this answer your question? [Catch an exception thrown by an async void method](https://stackoverflow.com/questions/5383310/catch-an-exception-thrown-by-an-async-void-method) – Cleptus Jan 11 '21 at 13:21

2 Answers2

0

I didn't get by what you mean crashes, because that's what happens when you throw exception. There are many ways to deal with this, one would be to return null and take a null result as product already exists. You also just return a string that says product already exists and product has been saved. It depends with what you want to achieve

0

you can use try catch in controller.

public async Task<ActionResult> Create([FromBody] CreateProductCommand createProductCommand)
{
    try
    {
        var userId = await Mediator.Send(createProductCommand);
    }
    catch (Exception ex)
    {

        if (ex.Message.Equals("Product Already Exists"))
        {
           // .... 
        }
        else
        {
          // consider rethrowing the exception here
          // otherwise exceptions with a different error message would go silent
        }
    }       


    if (userId != Guid.Empty)
    {
        return Ok();
    }
    return BadRequest(); // I want command error to be displayed here
}
Overlord
  • 2,740
  • 2
  • 18
  • 22
Cem
  • 1
  • 2