I encounter a very wierd error.
I have an Item with some properties that are JsonRequired.
When i try to call my route to get my Item when one property that is required is missing, my error is not automatically thrown as an error code 500 I get a 200 Ok instead.
Here is my route :
[HttpGet("{itemId}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<Item>> GetItemByIdAsync(long installationId, Guid itemId)
{
return await _itemService.GetItemByIdAsync(installationId, itemId);
}
Here is my Item class :
public class Item
{
[JsonProperty("id")]
[JsonRequired]
public Guid Id { get; set; }
[JsonProperty("name")]
[JsonRequired]
public string Name { get; set; }
}
And here is my middleware :
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (NotFoundException ex)
{
await HandleExceptionAsync(context, HttpStatusCode.NotFound, ex);
}
catch (UnauthorizedException ex)
{
await HandleExceptionAsync(context, HttpStatusCode.Unauthorized, ex, false);
}
catch (ConflictException ex)
{
await HandleExceptionAsync(context, HttpStatusCode.Conflict, ex);
}
catch (BadRequestException ex)
{
await HandleExceptionAsync(context, HttpStatusCode.BadRequest, ex);
}
}
private Task HandleExceptionAsync(HttpContext context, HttpStatusCode httpCode, Exception exception, bool displayException = true)
{
_logger.LogError(exception, $"Exception catched in middleware: {exception.Message}.");
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)httpCode;
var payload = JsonConvert.SerializeObject(new ApiError(displayException ? exception.Message : string.Empty));
return context.Response.WriteAsync(payload);
}
What I have tried : If I try to add this catch in the middleware
catch (Exception ex)
{
await HandleExceptionAsync(context, HttpStatusCode.InternalServerError, ex);
}
There is still the same result I don't get a 500 error. I don't really understand why my response is not overrided to be a 500 error. Do you have any idea ?
Thanks a lot.