How to handle validation exceptions in asp.net core webapi

1k Views Asked by At

I have an api controller which handles http post request like below

//controller
[Route("api/[controller]")]
[ApiController]
public class SomeController : ControllerBase
{
    //constructor here//

    [HttpPost]
    public async Task<IActionResult> Post(SomeModel model)
    {
        await handleData(model)  ;
        return Ok();
    }
}

//Model
public class SomeModel
{
    [Required]
    public string SomeProperty {get; set;}
}

for testing purpose when I try passing a boolean instead of string in the post request server responds with error

"$.field": [
            "The JSON value could not be converted to System.String. Path: $.field| LineNumber: 2 | BytePositionInLine: 16."
        ]

I tried catching the exception in the action method but since the validation happens before it even hits the action method how can I catch this exception and display an error message that would make sense to the user. Also how would I pass it back to the front end with the actual key/field that error happened on since the key in the error array is prepended with "$." . Thanks in advance

1

There are 1 best solutions below

0
On

You can specify error messages link

[StringLength(8, ErrorMessage = "Name length can't be more than 8.")]