Skip to content

Commit

Permalink
Merge pull request #53 from marcwittke/develop
Browse files Browse the repository at this point in the history
Develop
  • Loading branch information
marcwittke committed Dec 30, 2018
2 parents 76f3084 + 69484ed commit 7af4518
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 24 deletions.
17 changes: 13 additions & 4 deletions src/abstractions/Backend.Fx/Exceptions/ClientException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;


public class ClientException : Exception
{
Expand Down Expand Up @@ -48,21 +50,28 @@ public override string ToString()

public static class ClientExceptionEx
{
public static TEx AddError<TEx>(this TEx clientException, string errorMessage) where TEx : ClientException
public static TEx AddError<TEx>(this TEx clientException, [LocalizationRequired] string errorMessage) where TEx : ClientException
{
clientException.Errors.Add(errorMessage);
return clientException;
}

public static TEx AddError<TEx>(this TEx clientException, string key, string errorMessage) where TEx : ClientException
public static TEx AddError<TEx>(this TEx clientException, string key, [LocalizationRequired] string errorMessage) where TEx : ClientException
{
clientException.Errors.Add(key, errorMessage);
return clientException;
}

public static TEx AddErrors<TEx>(this TEx clientException, string key, IEnumerable<string> errorMessage) where TEx : ClientException
public static TEx AddErrors<TEx>(this TEx clientException, [LocalizationRequired] IEnumerable<string> errorMessages) where TEx : ClientException
{
clientException.Errors.Add(key, errorMessage);
clientException.Errors.Add(errorMessages);
return clientException;
}


public static TEx AddErrors<TEx>(this TEx clientException, string key, [LocalizationRequired] IEnumerable<string> errorMessages) where TEx : ClientException
{
clientException.Errors.Add(key, errorMessages);
return clientException;
}
}
Expand Down
6 changes: 6 additions & 0 deletions src/abstractions/Backend.Fx/Exceptions/Errors.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,12 @@ public Errors Add(string errorMessage)
return this;
}

public Errors Add(IEnumerable<string> errorMessages)
{
Add(GenericErrorKey, errorMessages);
return this;
}

public Errors Add(string key, IEnumerable<string> errorMessages)
{
if (!_dictionaryImplementation.ContainsKey(key))
Expand Down
24 changes: 11 additions & 13 deletions src/environments/Backend.Fx.AspNetCore/BackendFxProgram.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,18 @@
using Backend.Fx.NetCore.Logging;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

public class BackendFxProgram<TStartup> where TStartup : class
{
private static Logging.ILogger _logger = new DebugLogger(nameof(BackendFxProgram<TStartup>));
private static Backend.Fx.Logging.ILogger _logger = new DebugLogger(nameof(BackendFxProgram<TStartup>));

public virtual void Main(string[] args)
{
IWebHost webHost;
try
{
webHost = BuildWebHost(args);
webHost = CreateWebHostBuilder(args).Build();
}
catch (Exception ex)
{
Expand All @@ -36,13 +34,17 @@ public virtual void Main(string[] args)
catch (Exception ex)
{
_logger.Fatal(ex, "Web host died unexpectedly");
LogManager.Shutdown();
throw;
}
finally
{
LogManager.Shutdown();
}
}

public virtual IWebHost BuildWebHost(string[] args)
public IWebHostBuilder CreateWebHostBuilder(string[] args)
{

try
{
_logger = LogManager.Create<BackendFxProgram<TStartup>>();
Expand All @@ -56,7 +58,6 @@ public virtual IWebHost BuildWebHost(string[] args)

try
{
IWebHost host;
using (_logger.InfoDuration("Building web host"))
{
var webHostBuilder = WebHost.CreateDefaultBuilder(args)
Expand All @@ -71,21 +72,18 @@ public virtual IWebHost BuildWebHost(string[] args)

ConfigureWebHost(webHostBuilder);

host = webHostBuilder.Build();
host.Services.GetRequiredService<IApplicationLifetime>().ApplicationStopped.Register(LogManager.Shutdown);
return webHostBuilder;
}

return host;
}
catch (Exception ex)
{
_logger.Fatal(ex, "Web host could not be built.");
_logger.Fatal(ex, "Web host builder could not be created.");
LogManager.Shutdown();
throw;
}
}

protected virtual void ConfigureWebHost(IWebHostBuilder builder)
{}
{ }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,12 @@ public class JsonErrorHandlingMiddleware : ErrorHandlingMiddleware
{
private readonly IHostingEnvironment _env;
private static readonly ILogger Logger = LogManager.Create<JsonErrorHandlingMiddleware>();
private readonly JsonSerializerSettings _jsonSerializerSettings = new JsonSerializerSettings

protected JsonSerializerSettings JsonSerializerSettings { get; } = new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy { ProcessDictionaryKeys = true }
NamingStrategy = new CamelCaseNamingStrategy {ProcessDictionaryKeys = true}
},
};

Expand Down Expand Up @@ -53,10 +54,9 @@ protected override async Task HandleClientError(HttpContext context, int httpSta
: new Errors().Add($"HTTP{httpStatusCode}: {message}");

context.Response.StatusCode = httpStatusCode;
var errorsDictionaryForJson = errors.ToDictionary(kvp => kvp.Key == "" ? "_error" : kvp.Key, kvp => kvp.Value);
string responseContent = JsonConvert.SerializeObject(errorsDictionaryForJson, _jsonSerializerSettings);
string serializedErrors = SerializeErrors(errors);
context.Response.ContentType = "application/json; charset=utf-8";
await context.Response.WriteAsync(responseContent);
await context.Response.WriteAsync(serializedErrors);
}

protected override async Task HandleServerError(HttpContext context, Exception exception)
Expand All @@ -68,10 +68,16 @@ protected override async Task HandleServerError(HttpContext context, Exception e
}
context.Response.StatusCode = (int) HttpStatusCode.InternalServerError;
var responseContent = _env.IsDevelopment()
? JsonConvert.SerializeObject(new { message = exception.Message, stackTrace = exception.StackTrace }, _jsonSerializerSettings)
: JsonConvert.SerializeObject(new { message = "An internal error occured" }, _jsonSerializerSettings);
? JsonConvert.SerializeObject(new { message = exception.Message, stackTrace = exception.StackTrace }, JsonSerializerSettings)
: JsonConvert.SerializeObject(new { message = "An internal error occured" }, JsonSerializerSettings);
context.Response.ContentType = "application/json; charset=utf-8";
await context.Response.WriteAsync(responseContent);
}

protected virtual string SerializeErrors(Errors errors)
{
var errorsDictionaryForJson = errors.ToDictionary(kvp => kvp.Key == "" ? "_error" : kvp.Key, kvp => kvp.Value);
return JsonConvert.SerializeObject(errorsDictionaryForJson, JsonSerializerSettings);
}
}
}

0 comments on commit 7af4518

Please sign in to comment.