Hi all;
Is this a good way to handle exceptions globally?
In any razor.cs page I have:
catch (Exception ex)
{
ex.Data.Add("Category", typeof(CampaignPage));
throw;
}
And then in MainLayout.razor I have:
@inherits LayoutComponentBase
@inject ILoggerFactory LoggerFactory
@inject ILogger<MainLayout> Logger
<ErrorBoundary>
<ChildContent>
<div style="height: 100%; overflow-y: hidden;">
<div style="margin: 0; height: 100%; overflow-y: hidden;">
<div style="display: flex; flex-direction: column; height: 100%; overflow-y: hidden;">
<div style="width: 100%;">
<header>
<Banner ShowBanner="@SessionData.ShowWelcomeBanner"
OnBannerClosed="WelcomeBannerClosed"
BannerContent="Please complete your registration. <a href='/Admin/Welcome'>Click here for more information.</a>" />
</header>
</div>
<div style="width: 100%;">
<NavMenu />
</div>
<div style="flex-grow: 1; width: 100%; overflow: auto;">
<div style="height: 100%; overflow: auto;">
<main>
<div class="my-main-scrollbar">
<PopupMessageBox>
@Body
</PopupMessageBox>
</div>
</main>
</div>
</div>
<div style="width: 100%;">
<footer class="main-footer">
<span>© David Thielen 2023 - ALL RIGHTS RESERVED</span>
</footer>
</div>
</div>
</div>
</div>
</ChildContent>
<ErrorContent Context="error">
@{
var guid = Guid.NewGuid().ToString();
var useFallback = true;
if (error.Data.Contains("Category"))
{
var data = error.Data["Category"];
if (data is Type category)
{
var logger = LoggerFactory.CreateLogger(category);
logger.LogError(error, "Error: {guid}", guid);
useFallback = false;
}
}
if (useFallback)
{
Logger.LogError(error, "Error: {guid}", guid);
}
}
<h1>Unexpected Error (sorry)</h1>
<p>
The program has encountered an unexpected error (yes there are expected errors). This error has been
logged and we will look at it.
</p>
<p>We suggest you <a href="/identity/account/LogOut">logout</a> and then log back in if you wish to try again.</p>
<p>If you want to contact us, please include the following error id: @guid when you do.</p>
</ErrorContent>
</ErrorBoundary>
Is this a good way to globally handle exceptions?
I assign the Category to Exception.Data so that the category is for where it was thrown for when I filter the log. Otherwise every exception would be in the category of MainLayout.
thoughts - ??? - dave