App no longer crashes on startup when appsettings.json is absent (e.g. fresh clone). Configuration is loaded from appsettings.json if present, then overridden by appsettings.local.json if that exists. Both files are gitignored to keep secrets out of the repo. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
68 lines
2.4 KiB
C#
68 lines
2.4 KiB
C#
using System.Threading.Tasks;
|
|
using System.Windows;
|
|
using System.Windows.Threading;
|
|
using Microsoft.Extensions.Configuration;
|
|
|
|
namespace EbayListingTool;
|
|
|
|
public partial class App : Application
|
|
{
|
|
public static IConfiguration Configuration { get; private set; } = null!;
|
|
|
|
protected override void OnStartup(StartupEventArgs e)
|
|
{
|
|
// Global handler for unhandled exceptions on the UI thread
|
|
DispatcherUnhandledException += OnDispatcherUnhandledException;
|
|
|
|
// Global handler for unhandled exceptions on background Task threads
|
|
TaskScheduler.UnobservedTaskException += OnUnobservedTaskException;
|
|
|
|
// Global handler for unhandled exceptions on non-UI threads
|
|
AppDomain.CurrentDomain.UnhandledException += OnDomainUnhandledException;
|
|
|
|
Configuration = new ConfigurationBuilder()
|
|
.SetBasePath(AppContext.BaseDirectory)
|
|
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: false)
|
|
.AddJsonFile("appsettings.local.json", optional: true, reloadOnChange: false)
|
|
.Build();
|
|
|
|
base.OnStartup(e);
|
|
}
|
|
|
|
private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
|
|
{
|
|
MessageBox.Show(
|
|
$"An unexpected error occurred:\n\n{e.Exception.Message}",
|
|
"Unexpected Error",
|
|
MessageBoxButton.OK,
|
|
MessageBoxImage.Error);
|
|
e.Handled = true; // Prevent crash; remove this line if you want fatal errors to still terminate
|
|
}
|
|
|
|
private void OnUnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
|
|
{
|
|
e.SetObserved();
|
|
Dispatcher.InvokeAsync(() =>
|
|
{
|
|
MessageBox.Show(
|
|
$"A background operation failed:\n\n{e.Exception.InnerException?.Message ?? e.Exception.Message}",
|
|
"Background Error",
|
|
MessageBoxButton.OK,
|
|
MessageBoxImage.Warning);
|
|
});
|
|
}
|
|
|
|
private void OnDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
|
|
{
|
|
var message = e.ExceptionObject is Exception ex
|
|
? ex.Message
|
|
: e.ExceptionObject?.ToString() ?? "Unknown error";
|
|
|
|
MessageBox.Show(
|
|
$"A fatal error occurred and the application must close:\n\n{message}",
|
|
"Fatal Error",
|
|
MessageBoxButton.OK,
|
|
MessageBoxImage.Error);
|
|
}
|
|
}
|