Skip to content

propagate model state errors #320

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 29, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/JsonApiDotNetCore/Controllers/BaseJsonApiController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -146,13 +146,15 @@ public virtual async Task<IActionResult> GetRelationshipAsync(TId id, string rel

public virtual async Task<IActionResult> PostAsync([FromBody] T entity)
{
if (_create == null) throw Exceptions.UnSupportedRequestMethod;
if (_create == null)
throw Exceptions.UnSupportedRequestMethod;

if (entity == null)
return UnprocessableEntity();

if (!_jsonApiContext.Options.AllowClientGeneratedIds && !string.IsNullOrEmpty(entity.StringId))
return Forbidden();

if (_jsonApiContext.Options.ValidateModelState && !ModelState.IsValid)
return BadRequest(ModelState.ConvertToErrorCollection());

Expand Down
13 changes: 9 additions & 4 deletions src/JsonApiDotNetCore/Extensions/ModelStateExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,22 @@ public static class ModelStateExtensions
{
public static ErrorCollection ConvertToErrorCollection(this ModelStateDictionary modelState)
{
ErrorCollection errors = new ErrorCollection();
ErrorCollection collection = new ErrorCollection();
foreach (var entry in modelState)
{
if (!entry.Value.Errors.Any())
if (entry.Value.Errors.Any() == false)
continue;

foreach (var modelError in entry.Value.Errors)
{
errors.Errors.Add(new Error(400, entry.Key, modelError.ErrorMessage, modelError.Exception != null ? ErrorMeta.FromException(modelError.Exception) : null));
if (modelError.Exception is JsonApiException jex)
collection.Errors.AddRange(jex.GetError().Errors);
else
collection.Errors.Add(new Error(400, entry.Key, modelError.ErrorMessage, modelError.Exception != null ? ErrorMeta.FromException(modelError.Exception) : null));
}
}
return errors;

return collection;
}
}
}
6 changes: 2 additions & 4 deletions src/JsonApiDotNetCore/Formatters/JsonApiReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,9 @@ public Task<InputFormatterResult> ReadAsync(InputFormatterContext context)
context.ModelState.AddModelError(context.ModelName, ex, context.Metadata);
return InputFormatterResult.FailureAsync();
}
catch (JsonApiException jex)
catch (JsonApiException)
{
_logger?.LogError(new EventId(), jex, "An error occurred while de-serializing the payload");
context.ModelState.AddModelError(context.ModelName, jex, context.Metadata);
return InputFormatterResult.FailureAsync();
throw;
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/JsonApiDotNetCore/JsonApiDotNetCore.csproj
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<VersionPrefix>2.3.3</VersionPrefix>
<VersionPrefix>2.3.4</VersionPrefix>
<TargetFrameworks>$(NetStandardVersion)</TargetFrameworks>
<AssemblyName>JsonApiDotNetCore</AssemblyName>
<PackageId>JsonApiDotNetCore</PackageId>
Expand Down
13 changes: 11 additions & 2 deletions src/JsonApiDotNetCore/Serialization/JsonApiDeSerializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,10 @@ public object Deserialize(string requestBody)
var entity = DocumentToObject(document.Data, document.Included);
return entity;
}
catch (JsonApiException)
{
throw;
}
catch (Exception e)
{
throw new JsonApiException(400, "Failed to deserialize request body", e);
Expand Down Expand Up @@ -109,10 +113,15 @@ public List<TEntity> DeserializeList<TEntity>(string requestBody)

public object DocumentToObject(DocumentData data, List<DocumentData> included = null)
{
if (data == null) throw new JsonApiException(422, "Failed to deserialize document as json:api.");
if (data == null)
throw new JsonApiException(422, "Failed to deserialize document as json:api.");

var contextEntity = _jsonApiContext.ContextGraph.GetContextEntity(data.Type?.ToString());
_jsonApiContext.RequestEntity = contextEntity;
_jsonApiContext.RequestEntity = contextEntity ?? throw new JsonApiException(400,
message: $"This API does not contain a json:api resource named '{data.Type}'.",
detail: "This resource is not registered on the ContextGraph. "
+ "If you are using Entity Framework, make sure the DbSet matches the expected resource name. "
+ "If you have manually registered the resource, check that the call to AddResource correctly sets the public name."); ;

var entity = Activator.CreateInstance(contextEntity.EntityType);

Expand Down
26 changes: 26 additions & 0 deletions test/UnitTests/Models/IdentifiableTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using JsonApiDotNetCore.Models;
using Xunit;

namespace UnitTests.Models
{
public class IdentifiableTests
{
[Fact]
public void Can_Set_StringId_To_Value_Type()
{
var resource = new IntId();
resource.StringId = "1";
Assert.Equal(1, resource.Id);
}

[Fact]
public void Setting_StringId_To_Null_Sets_Id_As_Default()
{
var resource = new IntId();
resource.StringId = null;
Assert.Equal(0, resource.Id);
}

private class IntId : Identifiable { }
}
}