Earth
Earth

Reputation: 3571

How to throw error (Bad Request) in void method in Web API

How to throw error (Bad Request) in void method in Web API

public async Task UpdateRecord([FromBody] UpdateRecord model)
{
    try
    {
        await _recordService.UpdateRecord(model);
    }
    catch (Exception ex)
    {
        var message = new NetHttp.HttpResponseMessage(HttpStatusCode.BadRequest);
        message.Content = new NetHttp.StringContent(ex.Message);
        throw new WebHttp.HttpResponseException(message);
    }
}

In swagger, its showing as 500. But I have mentioned 400 - Bad Request

Upvotes: 1

Views: 1476

Answers (2)

Earth
Earth

Reputation: 3571

I have updated as below after got advise from Athanasios Kataras.

public async Task<IActionResult> UpdateRecord([FromBody] UpdateRecord model)
  {
        try
        {
             await _recordService.UpdateRecord(model);
        }
        catch (Exception ex)
        {
             return BadRequest(ex.Message);
        }
    
        return Ok(); // Not passing any value inside
  }

Upvotes: 0

Athanasios Kataras
Athanasios Kataras

Reputation: 26432

Since you are throwing an exception it will always be 500 (if you are not catching it anywhere else).

If you want a bad request, then

public async Task<IHttpActionResult> UpdateRecord([FromBody] UpdateRecord model)
{
    try
    {
        await _recordService.UpdateRecord(model);
    }
    catch (Exception ex)
    {
        return BadRequest(/*Optional message*/);
    }
    return Ok(returnData);
}

I would advise you though to rethink your strategy as:

  1. Unhandled exceptions should not be happening normally in your application. Should they happen, then the 500 family is the proper Http code to return.
  2. You can see that BadRequest expects some validation errors. While not mandatory, this error code assumes there is some type of wrong input data in terms of format and not business logic.

You can though serve this without a validation message

return BadRequest();

Upvotes: 1

Related Questions