Skip to content

Instantly share code, notes, and snippets.

@justinyoo
Last active March 23, 2016 10:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justinyoo/df11d6f4aa5e1753c30e to your computer and use it in GitHub Desktop.
Save justinyoo/df11d6f4aa5e1753c30e to your computer and use it in GitHub Desktop.
ASP.NET Core Tips & Tricks
public class Startup
{
private const string ExceptionsOnStartup = "Startup";
private const string ExceptionsOnConfigureServices = "ConfigureServices";
private readonly Dictionary<string, List<Exception>> _exceptions;
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv, ILoggerFactory logger, string[] args = null)
{
this._exceptions = new Dictionary<string, List<Exception>>
{
{ ExceptionsOnStartup, new List<Exception>() },
{ ExceptionsOnConfigureServices, new List<Exception>() },
};
try
{
...
}
catch (Exception ex)
{
this._exceptions[ExceptionsOnStartup].Add(ex);
}
}
...
public IServiceProvider ConfigureServices(IServiceCollection services)
{
try
{
...
}
catch (Exception ex)
{
this._exceptions[ExceptionsOnConfigureServices].Add(ex);
return null;
}
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory logger)
{
logger.AddConsole(this.Configuration.GetSection("Logging"));
logger.AddDebug();
var log = logger.CreateLogger<Startup>();
if (this._exceptions.Any(p => p.Value.Any()))
{
app.Run(
async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.ContentType = "text/plain";
foreach (var ex in this._exceptions)
{
foreach (var val in ex.Value)
{
log.LogError($"{ex.Key}:::{val.Message}");
await context.Response.WriteAsync($"Error on {ex.Key}: {val.Message}").ConfigureAwait(false);
}
}
});
return;
}
...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment