1

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

Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61
Earth
  • 3,477
  • 6
  • 37
  • 78
  • About the specific ranges in the HTTP status: 2xx OK 4xx Client error link 404 for you are using a wrong path which is not exiting 5xx Server error like process is crashed during a exception Sending BadRequest may not fit common DB exceptions, if the DB connection is not valid or your have a double primary key, null value exceptions etc. – coding Bott Dec 09 '22 at 11:54

2 Answers2

1

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();
Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61
  • Thanks for your answer. Here the challenge is method return type is `void`. How can we achieve when the method return type is void. I can't return any data for success. Just for error, I need to mention as `Bad Request` – Earth Dec 09 '22 at 11:33
  • You are retruning data for success anyway. The Ok() method returns http code 200 without any data. The same thing happens with the Task return type, only without returning the Ok(); – Athanasios Kataras Dec 09 '22 at 11:34
  • I have removed return type and keep it void in service and data layer. Ok, So, I will update it accordingly. – Earth Dec 09 '22 at 11:36
  • 1
    Cheers! Don't forget to upvote/accept helpful answers! – Athanasios Kataras Dec 09 '22 at 11:37
  • Is that ResponseMessage or HttpResponseMessage. Also, CreateResponse showing error saying does not have 2 arguments – Earth Dec 09 '22 at 11:47
  • Check the edited answer. No need to go at all with the RepsonseMessage class, just return the BadRequest. – Athanasios Kataras Dec 09 '22 at 11:49
  • ok, also it seems to be IActionResult instead of IHttpActionResult, I think because am getting not supported error – Earth Dec 09 '22 at 11:50
  • Also, as the API does not returning data in success, what type I can declare in the service and data layer for the method return types. In controller, I can mention as IActionResult, but in service and data layer instead of void what return type can I mention – Earth Dec 09 '22 at 11:54
  • Whatever you want. There is no need for the service/data layer to return the same type as the controller. Separation of concerns mandates that there is no coupling between the layers either logical or code. – Athanasios Kataras Dec 09 '22 at 14:51
0

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
  }
Earth
  • 3,477
  • 6
  • 37
  • 78