Skip to content

Commit

Permalink
Merge a1d6578 into 53e325d
Browse files Browse the repository at this point in the history
  • Loading branch information
andreloureiro88 committed Mar 21, 2022
2 parents 53e325d + a1d6578 commit cf46743
Show file tree
Hide file tree
Showing 14 changed files with 207 additions and 13 deletions.
8 changes: 8 additions & 0 deletions src/Castle.Sdk/Actions/Authenticate.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ internal static class Authenticate
{
return await send();
}
catch (Exception e) when (e is CastleNotFoundException || e is CastleInvalidTokenException || e is CastleInvalidParametersException)
{
throw e;
}
catch (Exception e)
{
logger.Warn(() => "Failover, " + e);
Expand All @@ -40,6 +44,10 @@ private static Verdict CreateFailoverResponse(ActionType strategy, string reason
return new Verdict()
{
Action = strategy,
Policy = new Policy
{
Action = strategy
},
Failover = true,
FailoverReason = reason
};
Expand Down
8 changes: 8 additions & 0 deletions src/Castle.Sdk/Actions/Filter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ internal static class Filter
{
return await send();
}
catch (Exception e) when (e is CastleNotFoundException || e is CastleInvalidTokenException || e is CastleInvalidParametersException)
{
throw e;
}
catch (Exception e)
{
logger.Warn(() => "Failover, " + e);
Expand All @@ -36,6 +40,10 @@ private static RiskResponse CreateFailoverResponse(ActionType strategy, string r
return new RiskResponse()
{
Action = strategy,
Policy = new Policy
{
Action = strategy
},
Failover = true,
FailoverReason = reason
};
Expand Down
8 changes: 8 additions & 0 deletions src/Castle.Sdk/Actions/Risk.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ internal static class Risk
{
return await send();
}
catch (Exception e) when (e is CastleNotFoundException || e is CastleInvalidTokenException || e is CastleInvalidParametersException)
{
throw e;
}
catch (Exception e)
{
logger.Warn(() => "Failover, " + e);
Expand All @@ -36,6 +40,10 @@ private static RiskResponse CreateFailoverResponse(ActionType strategy, string r
return new RiskResponse()
{
Action = strategy,
Policy = new Policy
{
Action = strategy
},
Failover = true,
FailoverReason = reason
};
Expand Down
15 changes: 15 additions & 0 deletions src/Castle.Sdk/Castle.Sdk.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion src/Castle.Sdk/Headers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ public static class Headers
"TE",
"Upgrade-Insecure-Requests",
"User-Agent",
"X-Castle-Client-Id",
"X-Requested-With"
};
}
Expand Down
4 changes: 4 additions & 0 deletions src/Castle.Sdk/Infrastructure/ExceptionGuard.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ internal static class ExceptionGuard
{
throw;
}
catch (Exception e) when (e is CastleNotFoundException || e is CastleInvalidTokenException || e is CastleInvalidParametersException)
{
throw e;
}
catch (Exception e)
{
logger.Error(e.ToString);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using System;
using System.Net;

namespace Castle.Infrastructure.Exceptions
{
/// <summary>
/// Exception for Unprocessable Entity
/// </summary>
internal class CastleInvalidParametersException : Exception
{
public CastleInvalidParametersException(string message, string requestUri, HttpStatusCode? httpStatusCode = null)
: base(message)
{
HttpStatusCode = httpStatusCode;
RequestUri = requestUri;
}

public HttpStatusCode? HttpStatusCode { get; set; }

public string RequestUri { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using System;
using System.Net;

namespace Castle.Infrastructure.Exceptions
{
/// <summary>
/// Exception for Invalid request token
/// </summary>
internal class CastleInvalidTokenException : Exception
{
public CastleInvalidTokenException(string message, string requestUri, HttpStatusCode? httpStatusCode = null)
: base(message)
{
HttpStatusCode = httpStatusCode;
RequestUri = requestUri;
}

public HttpStatusCode? HttpStatusCode { get; set; }

public string RequestUri { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using System;
using System.Net;

namespace Castle.Infrastructure.Exceptions
{
/// <summary>
/// Exception for route not found
/// </summary>
internal class CastleNotFoundException : Exception
{
public CastleNotFoundException(string message, string requestUri, HttpStatusCode? httpStatusCode = null)
: base(message)
{
HttpStatusCode = httpStatusCode;
RequestUri = requestUri;
}

public HttpStatusCode? HttpStatusCode { get; set; }

public string RequestUri { get; set; }
}
}
36 changes: 34 additions & 2 deletions src/Castle.Sdk/Infrastructure/Extensions/HttpResponseExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,46 @@
using System.Net.Http;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using Castle.Infrastructure.Exceptions;
using Castle.Infrastructure.Json;

namespace Castle.Infrastructure.Extensions
{
internal static class HttpResponseExtensions
{
public static async Task<CastleInternalException> ToCastleException(this HttpResponseMessage message, string requestUri)
public static async Task<Exception> ToCastleException(this HttpResponseMessage message, string requestUri)
{

if (message.StatusCode == HttpStatusCode.NotFound)
{
throw new CastleNotFoundException("Not Found", requestUri, message.StatusCode);
}
var content = await message.Content.ReadAsStringAsync();
if ((int)message.StatusCode == 422)
{

try
{
var parsedContent = JsonForCastle.DeserializeObject<Dictionary<string, string>>(content);
if (parsedContent.ContainsKey("type"))
{
if (parsedContent["type"] == "invalid_request_token")
{
throw new CastleInvalidTokenException(parsedContent["message"], requestUri, message.StatusCode);
}
throw new CastleInvalidParametersException(parsedContent["message"], requestUri, message.StatusCode);
}
}
catch (JsonException)
{
return new CastleInternalException(content, requestUri, message.StatusCode);
}
throw new CastleInvalidParametersException(content, requestUri, message.StatusCode);
}

return new CastleInternalException(content, requestUri, message.StatusCode);
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/Castle.Sdk/Messages/Responses/Verdict.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ namespace Castle.Messages.Responses
public class Verdict : IHasJson
{
public ActionType Action { get; set; }

public Policy Policy { get; set; }
public string UserId { get; set; }

public string DeviceToken { get; set; }
Expand Down
14 changes: 14 additions & 0 deletions src/Tests/Actions/When_sending_filter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,5 +75,19 @@ public class When_sending_filter
await act.Should().ThrowAsync<CastleExternalException>();
}

[Theory, AutoFakeData]
public async Task Should_throw_exception_if_route_not_found(
CastleConfiguration configuration)
{
configuration.FailOverStrategy = ActionType.None;
var logger = Substitute.For<IInternalLogger>();

Task<RiskResponse> Send() => throw new CastleNotFoundException("Not Found", "someurl", System.Net.HttpStatusCode.NotFound);

Func<Task> act = async () => await Filter.Execute(Send, configuration, logger);

await act.Should().ThrowAsync<CastleNotFoundException>();
}

}
}
49 changes: 44 additions & 5 deletions src/Tests/Sending/When_converting_http_messages.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
using System.Net.Http;
using System;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using AutoFixture.Xunit2;
using Castle.Infrastructure.Exceptions;
using Castle.Infrastructure.Extensions;
using FluentAssertions;
using Newtonsoft.Json;
using Tests.SetUp;
using Xunit;

Expand All @@ -23,11 +28,45 @@ public void Should_create_stringcontent_from_payload(object payload)
[Theory, AutoFakeData]
public async Task Should_create_exception_from_httpresponse(HttpResponseMessage response, string uri)
{
var result = await response.ToCastleException(uri);
try
{
var result = await response.ToCastleException(uri);
}
catch (Exception e)
{
Assert.True(e is CastleInternalException);
}

result.HttpStatusCode.Should().Be(response.StatusCode);
result.RequestUri.Should().Be(uri);
result.Message.Should().Be(await response.Content.ReadAsStringAsync());
}

[Theory, AutoFakeData]
public void Should_create_exception_from_httpresponse_not_found(HttpResponseMessage response, string uri)
{

response.StatusCode = HttpStatusCode.NotFound;
Func<Task> act = async () => await response.ToCastleException(uri);
act.Should().Throw<CastleNotFoundException>();
}

[Theory, AutoFakeData]
public void Should_create_exception_from_httpresponse_invalid_token(HttpResponseMessage response, string uri)
{
response.StatusCode = (HttpStatusCode)422;
response.Content = new StringContent("{'type': 'invalid_request_token','message': 'the token is not valid'}", Encoding.UTF8, "application/json");

Func<Task> act = async () => await response.ToCastleException(uri);
act.Should().Throw<CastleInvalidTokenException>();

}

[Theory, AutoFakeData]
public void Should_create_exception_from_httpresponse_invalid_parameters(HttpResponseMessage response, string uri)
{
response.StatusCode = (HttpStatusCode)422;
response.Content = new StringContent("{'message': 'parameters are invalid'}", Encoding.UTF8, "application/json");

Func<Task> act = async () => await response.ToCastleException(uri);
act.Should().Throw<CastleInvalidParametersException>();
}
}
}
9 changes: 5 additions & 4 deletions src/Tests/Sending/When_sending_requests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public class When_sending_requests
.Received()
.Info(Arg.Is<Func<string>>(func => func()
.StartsWith("Response")));
}
}
}

[Theory, AutoFakeData(typeof(HttpMessageHandlerSuccessCustomization))]
Expand All @@ -62,7 +62,7 @@ public class When_sending_requests
{
var result = await testMethod(sut);
result.Should().BeOfType<VoidResponse>();
}
}
}

[Theory, AutoFakeData(typeof(HttpMessageHandlerFailureCustomization))]
Expand All @@ -77,7 +77,7 @@ public class When_sending_requests
{
Func<Task> act = async () => await testMethod(sut);
act.Should().Throw<CastleInternalException>();
}
}
}

[Theory, AutoFakeData(typeof(HttpMessageHandlerCancelledCustomization))]
Expand All @@ -92,7 +92,7 @@ public class When_sending_requests
{
Func<Task> act = async () => await testMethod(sut);
act.Should().Throw<CastleTimeoutException>();
}
}
}

private static readonly Func<HttpMessageSender, Task<VoidResponse>>[] TestMethods =
Expand All @@ -103,5 +103,6 @@ public class When_sending_requests
async sender => await sender.Delete<VoidResponse>("", new { })
};


}
}

0 comments on commit cf46743

Please sign in to comment.