简体   繁体   中英

ASP.NET Core catch and display error inside Program.cs and Startup.cs

I am transferring my application to other hosting and have trouble setting it up.

I created blank asp.net core 2.1 application and deployed it to hosting and it works. After that i added connection string to database and tried reading from it and it also works. Then i deployed my already working application to that hosting and it is not working. Only problem i see there is something is wrong inside Program.cs or Startup.cs but how can i display try/catch error i put inside those files?

You cannot render HTML page with error in the web browser, because at this point application is not configured/running correctly.

Correct approach is investigate error logs, wherever they are stored (depends on your hosting company). If that is not possible, maybe you can hack your way around and make application write error in text files in it's own folders.

Another part of the problem, you need to wrap initialization in try/catch block, in order to log error. There is good example how to do that on Serilog.AspNetCore integration page :

using Serilog;

public class Program
{
    public static int Main(string[] args)
    {
        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Debug()
            .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
            .Enrich.FromLogContext()
            .WriteTo.Console()
            .CreateLogger();

        try
        {
            Log.Information("Starting web host");
            CreateHostBuilder(args).Build().Run();
            return 0;
        }
        catch (Exception ex)
        {
            Log.Fatal(ex, "Host terminated unexpectedly");
            return 1;
        }
        finally
        {
            Log.CloseAndFlush();
        }
    }

You would just need to modify this code to write to file with Serilog.Sinks.File extension. Examples are here .

var log = new LoggerConfiguration()
    .WriteTo.File("log.txt", rollingInterval: RollingInterval.Day)
    .CreateLogger();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM