From e98e46c728ce6ab0673e084d40ac130c03c16e40 Mon Sep 17 00:00:00 2001 From: Haacked Date: Thu, 10 Oct 2013 22:10:05 -0700 Subject: [PATCH] Make ApiError is never null --- .../Exceptions/ApiValidationExceptionTests.cs | 19 ++++++++++++++++++- Octokit/Exceptions/ApiValidationException.cs | 10 +++++++--- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/Octokit.Tests/Exceptions/ApiValidationExceptionTests.cs b/Octokit.Tests/Exceptions/ApiValidationExceptionTests.cs index 06f26e27..8e1a2049 100644 --- a/Octokit.Tests/Exceptions/ApiValidationExceptionTests.cs +++ b/Octokit.Tests/Exceptions/ApiValidationExceptionTests.cs @@ -1,4 +1,5 @@ -using System.IO; +using System; +using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using NSubstitute; @@ -39,6 +40,22 @@ namespace Octokit.Tests.Exceptions Assert.Equal(responseContent, exception.ApiValidationError.Message); } + [Fact] + public void CreatesEmptyGitHubErrorWhenResponseBodyIsNull() + { + var response = Substitute.For(); + response.Body.Returns("test"); + + var exception = new ApiValidationException(); + var anotherException = new ApiValidationException("message1"); + var thirdException = new ApiValidationException("message2", new InvalidOperationException()); + + // It's fine if the message is null when there's no response body as long as this doesn't throw. + Assert.Null(exception.ApiValidationError.Message); + Assert.Equal("message1", anotherException.ApiValidationError.Message); + Assert.Equal("message2", thirdException.ApiValidationError.Message); + } + #if !NETFX_CORE [Fact] public void CanPopulateObjectFromSerializedData() diff --git a/Octokit/Exceptions/ApiValidationException.cs b/Octokit/Exceptions/ApiValidationException.cs index ad386ba9..f3f49cff 100644 --- a/Octokit/Exceptions/ApiValidationException.cs +++ b/Octokit/Exceptions/ApiValidationException.cs @@ -17,16 +17,17 @@ namespace Octokit static readonly IJsonSerializer _jsonSerializer = new SimpleJsonSerializer(); public ApiValidationException() + : this(new ApiError(), null) { } public ApiValidationException(string message) - : base(message) + : this(new ApiError { Message = message }, null) { } public ApiValidationException(string message, Exception innerException) - : base(message, innerException) + : this(new ApiError { Message = message }, innerException) { } @@ -75,7 +76,10 @@ namespace Octokit try { if (responseContent != null) - return _jsonSerializer.Deserialize(responseContent) ?? new ApiError { Message = responseContent }; + { + return _jsonSerializer.Deserialize(responseContent) + ?? new ApiError { Message = responseContent }; + } } catch (Exception) {