Formatting error responses
yesmarket opened this issue · 2 comments
I would like to be able to have code
, status
, etc in error responses as per https://jsonapi.org/format/#error-objects.
Example is https://jsonapi.org/examples/#error-objects-basics
I'm throwing custom exception in my Web API project, but the error response is always :
{
"errors": [
{
"error": "test"
}
]
}
(where "test" is my exception message).
Is this in-line with the spec? I can't see 'error' defined in https://jsonapi.org/format/#error-objects
How would I go about getting code
, status
, etc into the error response?
There is a good chance that the response is not coming from the serializer.
If you have a response that includes error objects (https://github.com/codecutout/JsonApiSerializer/blob/master/src/JsonApiSerializer/JsonApi/Error.cs) then the serializer will format them correctly. However it doesn't map the exception to the error object
If you have a response that includes error objects then the serializer will format them correctly. However it doesn't map the exception to the error object
What Alex specifically means is that:
// JsonApiSerializer.JsonApi.Error
var error = new Error {
Status = "400",
Code = "BAD_REQUEST",
Title = "Bad Request",
Detail = "The request you've sent is invalid"
}
var json = JsonConvert.SerializeObject(error, new JsonApiSerializerSettings());
return Results.Content(json, "application/vnd.api+json", 400);
you can for example create your own reusable error objects by extending the Error class and then just serializing them like
JsonConvert.SerializeObject(new MyContentTypeError(), new JsonApiSerializerSettings())
But keep in mind that this is fundamentally different from throwing exceptions. If you do prefer to throw exceptions, you would need to create your own middleware / exception handler doing basically what i've demonstrated above