Skip to content
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

Show helpful error when ActionResult returns unsupported type #753

Merged
merged 2 commits into from
May 15, 2020
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
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,9 @@ public override async Task<IActionResult> PostAsync(TodoItem entity)
[HttpPatch("{id}")]
public override async Task<IActionResult> PatchAsync(int id, [FromBody] TodoItem entity)
{
return await base.PatchAsync(id, entity);
await Task.Yield();

return Conflict("Something went wrong");
}

[HttpPatch("{id}/relationships/{relationshipName}")]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public interface IRequestSerializer
/// </summary>
/// <param name="entities">Entities to serialize</param>
/// <returns>The serialized content</returns>
string Serialize(IEnumerable entities);
string Serialize(IEnumerable<IIdentifiable> entities);
/// <summary>
/// Sets the attributes that will be included in the serialized payload.
/// You can use <see cref="IResourceGraph.GetAttributes{TResource}"/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public string Serialize(IIdentifiable entity)
}

/// <inheritdoc/>
public string Serialize(IEnumerable entities)
public string Serialize(IEnumerable<IIdentifiable> entities)
{
IIdentifiable entity = null;
foreach (IIdentifiable item in entities)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ protected Document Build(IIdentifiable entity, IReadOnlyCollection<AttrAttribute
/// <param name="attributes">Attributes to include in the building process</param>
/// <param name="relationships">Relationships to include in the building process</param>
/// <returns>The resource object that was built</returns>
protected Document Build(IEnumerable entities, IReadOnlyCollection<AttrAttribute> attributes, IReadOnlyCollection<RelationshipAttribute> relationships)
protected Document Build(IEnumerable<IIdentifiable> entities, IReadOnlyCollection<AttrAttribute> attributes, IReadOnlyCollection<RelationshipAttribute> relationships)
{
var data = new List<ResourceObject>();
foreach (IIdentifiable entity in entities)
Expand Down
22 changes: 17 additions & 5 deletions src/JsonApiDotNetCore/Serialization/Server/ResponseSerializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Collections.Generic;
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.Extensions;
using JsonApiDotNetCore.Internal;
using JsonApiDotNetCore.Models;
using Newtonsoft.Json;
using JsonApiDotNetCore.Managers.Contracts;
Expand Down Expand Up @@ -54,11 +55,22 @@ public class ResponseSerializer<TResource> : BaseDocumentBuilder, IJsonApiSerial
/// <inheritdoc/>
public string Serialize(object data)
{
if (data == null || data is IIdentifiable)
{
return SerializeSingle((IIdentifiable)data);
}

if (data is IEnumerable<IIdentifiable> collectionOfIdentifiable)
{
return SerializeMany(collectionOfIdentifiable);
}

if (data is ErrorDocument errorDocument)
{
return SerializeErrorDocument(errorDocument);
if (data is IEnumerable entities)
return SerializeMany(entities);
return SerializeSingle((IIdentifiable)data);
}

throw new InvalidOperationException("Data being returned must be errors or resources.");
}

private string SerializeErrorDocument(ErrorDocument errorDocument)
Expand Down Expand Up @@ -102,11 +114,11 @@ internal string SerializeSingle(IIdentifiable entity)
/// <remarks>
/// This method is set internal instead of private for easier testability.
/// </remarks>
internal string SerializeMany(IEnumerable entities)
internal string SerializeMany(IEnumerable<IIdentifiable> entities)
{
var (attributes, relationships) = GetFieldsToSerialize();
var document = Build(entities, attributes, relationships);
foreach (ResourceObject resourceObject in (IEnumerable)document.Data)
foreach (ResourceObject resourceObject in document.ManyData)
{
var links = _linkBuilder.GetResourceLinks(resourceObject.Type, resourceObject.Id);
if (links == null)
Expand Down
36 changes: 36 additions & 0 deletions test/JsonApiDotNetCoreExampleTests/Acceptance/ActionResultTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,5 +77,41 @@ public async Task Empty_ActionResult_Is_Converted_To_Error_Collection()
Assert.Equal("NotFound", errorDocument.Errors[0].Title);
Assert.Null(errorDocument.Errors[0].Detail);
}

[Fact]
public async Task ActionResult_With_String_Object_Is_Converted_To_Error_Collection()
{
// Arrange
var route = "/abstract/123";
var request = new HttpRequestMessage(HttpMethod.Patch, route);
var content = new
{
data = new
{
type = "todoItems",
id = 123,
attributes = new Dictionary<string, object>
{
{"ordinal", 1}
}
}
};

request.Content = new StringContent(JsonConvert.SerializeObject(content));
request.Content.Headers.ContentType = new MediaTypeHeaderValue(HeaderConstants.MediaType);

// Act
var response = await _fixture.Client.SendAsync(request);

// Assert
var body = await response.Content.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);

var errorDocument = JsonConvert.DeserializeObject<ErrorDocument>(body);
Assert.Single(errorDocument.Errors);
Assert.Equal(HttpStatusCode.InternalServerError, errorDocument.Errors[0].StatusCode);
Assert.Equal("An unhandled error occurred while processing this request.", errorDocument.Errors[0].Title);
Assert.Equal("Data being returned must be errors or resources.", errorDocument.Errors[0].Detail);
}
}
}
2 changes: 1 addition & 1 deletion test/UnitTests/Serialization/SerializerTestsSetup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ public new Document Build(IIdentifiable entity, IReadOnlyCollection<AttrAttribut
return base.Build(entity, attributes, relationships);
}

public new Document Build(IEnumerable entities, IReadOnlyCollection<AttrAttribute> attributes = null, IReadOnlyCollection<RelationshipAttribute> relationships = null)
public new Document Build(IEnumerable<IIdentifiable> entities, IReadOnlyCollection<AttrAttribute> attributes = null, IReadOnlyCollection<RelationshipAttribute> relationships = null)
{
return base.Build(entities, attributes, relationships);
}
Expand Down