Aleksa Ristic
Aleksa Ristic

Reputation: 2499

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?

Upvotes: 2

Views: 2832

Answers (1)

Nenad
Nenad

Reputation: 26647

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();

Upvotes: 1

Related Questions