From 1506270b3a46752f45a9491c5ef8b8e063d69e21 Mon Sep 17 00:00:00 2001 From: Ryan Tablada Date: Tue, 28 Aug 2018 16:11:52 -0700 Subject: [PATCH] feat: error status code should be first in collection --- .../Internal/JsonApiException.cs | 2 +- .../Internal/JsonApiException_Test.cs | 31 +++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 test/UnitTests/Internal/JsonApiException_Test.cs diff --git a/src/JsonApiDotNetCore/Internal/JsonApiException.cs b/src/JsonApiDotNetCore/Internal/JsonApiException.cs index 8918d07c6c..49dc557e51 100644 --- a/src/JsonApiDotNetCore/Internal/JsonApiException.cs +++ b/src/JsonApiDotNetCore/Internal/JsonApiException.cs @@ -41,7 +41,7 @@ public JsonApiException(int statusCode, string message, Exception innerException public int GetStatusCode() { - if (_errors.Errors.Count == 1) + if (_errors.Errors.Select(a => a.StatusCode).Distinct().Count() == 1) return _errors.Errors[0].StatusCode; if (_errors.Errors.FirstOrDefault(e => e.StatusCode >= 500) != null) diff --git a/test/UnitTests/Internal/JsonApiException_Test.cs b/test/UnitTests/Internal/JsonApiException_Test.cs new file mode 100644 index 0000000000..57ac29d480 --- /dev/null +++ b/test/UnitTests/Internal/JsonApiException_Test.cs @@ -0,0 +1,31 @@ +using JsonApiDotNetCore.Internal; +using Xunit; + +namespace UnitTests.Internal +{ + public class JsonApiException_Test + { + [Fact] + public void Can_GetStatusCode() + { + var errors = new ErrorCollection(); + var exception = new JsonApiException(errors); + + // Add First 422 error + errors.Add(new Error(422, "Something wrong")); + Assert.Equal(422, exception.GetStatusCode()); + + // Add a second 422 error + errors.Add(new Error(422, "Something else wrong")); + Assert.Equal(422, exception.GetStatusCode()); + + // Add 4xx error not 422 + errors.Add(new Error(401, "Unauthorized")); + Assert.Equal(400, exception.GetStatusCode()); + + // Add 5xx error not 4xx + errors.Add(new Error(502, "Not good")); + Assert.Equal(500, exception.GetStatusCode()); + } + } +}