-
-
Save justinyoo/df11d6f4aa5e1753c30e to your computer and use it in GitHub Desktop.
ASP.NET Core Tips & Tricks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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