refactored ErrorBoundary implementation to support logging

This commit is contained in:
Shaun Walker 2021-11-22 16:11:44 -05:00
parent 59850f4869
commit 19be77ed49
6 changed files with 161 additions and 143 deletions

View File

@ -65,8 +65,8 @@
} }
catch (Exception ex) catch (Exception ex)
{ {
await logger.LogError(ex, "An Error Occurred Loading Html/Text Content. " + ex.Message); await logger.LogError(ex, "Error Loading Content {Error}", ex.Message);
AddModuleMessage(ex.Message, MessageType.Error); AddModuleMessage(Localizer["Error.Content.Load"], MessageType.Error);
} }
} }
@ -91,7 +91,7 @@
await HtmlTextService.AddHtmlTextAsync(htmltext); await HtmlTextService.AddHtmlTextAsync(htmltext);
} }
await logger.LogInformation("Html/Text Content Saved {HtmlText}", htmltext); await logger.LogInformation("Content Saved {HtmlText}", htmltext);
NavigationManager.NavigateTo(NavigateUrl()); NavigationManager.NavigateTo(NavigateUrl());
} }
catch (Exception ex) catch (Exception ex)

View File

@ -15,16 +15,16 @@
} }
@code { @code {
public override List<Resource> Resources => new List<Resource>() public override List<Resource> Resources => new List<Resource>()
{ {
new Resource { ResourceType = ResourceType.Stylesheet, Url = ModulePath() + "Module.css" } new Resource { ResourceType = ResourceType.Stylesheet, Url = ModulePath() + "Module.css" }
}; };
private string content = ""; private string content = "";
protected override async Task OnParametersSetAsync() protected override async Task OnParametersSetAsync()
{ {
try try
{ {
var htmltext = await HtmlTextService.GetHtmlTextAsync(ModuleState.ModuleId); var htmltext = await HtmlTextService.GetHtmlTextAsync(ModuleState.ModuleId);
if (htmltext != null) if (htmltext != null)
@ -35,8 +35,8 @@
} }
catch (Exception ex) catch (Exception ex)
{ {
await logger.LogError(ex, "An Error Occurred Loading Html/Text Content. " + ex.Message); await logger.LogError(ex, "Error Loading Content {Error}", ex.Message);
AddModuleMessage(ex.Message, MessageType.Error); AddModuleMessage(Localizer["Error.Content.Load"], MessageType.Error);
} }
} }
} }

View File

@ -117,7 +117,10 @@
<resheader name="writer"> <resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </resheader>
<data name="Error.Content.Load" xml:space="preserve">
<value>An Error Occurred Loading Content</value>
</data>
<data name="Error.Content.Save" xml:space="preserve"> <data name="Error.Content.Save" xml:space="preserve">
<value>Error Saving Content</value> <value>An Error Occurred Saving Content</value>
</data> </data>
</root> </root>

View File

@ -1,65 +1,65 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<root> <root>
<!-- <!--
Microsoft ResX Schema Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
Version 2.0 mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
The primary goals of this format is to allow a simple XML format : using a System.ComponentModel.TypeConverter
that is mostly human readable. The generation and parsing of the : and then encoded with base64 encoding.
various data types are done through the TypeConverter classes -->
associated with the data types. <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" id="root">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" /> <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true"> <xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType> <xsd:complexType>
@ -120,4 +120,7 @@
<data name="Edit.Action" xml:space="preserve"> <data name="Edit.Action" xml:space="preserve">
<value>Edit</value> <value>Edit</value>
</data> </data>
<data name="Error.Content.Load" xml:space="preserve">
<value>An Error Occurred Loading Content</value>
</data>
</root> </root>

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<root> <root>
<!-- <!--
Microsoft ResX Schema Microsoft ResX Schema
@ -124,6 +124,6 @@
<value>Module Type Is Invalid For {0}</value> <value>Module Type Is Invalid For {0}</value>
</data> </data>
<data name="Error.Module.Exception" xml:space="preserve"> <data name="Error.Module.Exception" xml:space="preserve">
<value>Program error in module {0}</value> <value>An Unexpected Error Has Occurred</value>
</data> </data>
</root> </root>

View File

@ -1,92 +1,104 @@
@namespace Oqtane.UI @namespace Oqtane.UI
@inject IStringLocalizer<ModuleInstance> Localizer @inject IStringLocalizer<ModuleInstance> Localizer
@inject ILogService LoggingService
@inherits ErrorBoundary
<ErrorBoundary> @if (CurrentException is null)
<ErrorContent> {
<ModuleMessage Message="@ErrorMessage(context)" Type="@MessageType.Error"/> <ModuleMessage Message="@_message" Type="@_messageType"/>
</ErrorContent> @if (ModuleType != null)
<ChildContent> {
<ModuleMessage Message="@_message" Type="@_messageType"/> <DynamicComponent Type="@ModuleType" Parameters="@ModuleParameters"></DynamicComponent>
@if (ModuleType != null) @if (_progressIndicator)
{ {
<DynamicComponent Type="@ModuleType" Parameters="@ModuleParameters"></DynamicComponent> <div class="app-progress-indicator"></div>
@if (_progressIndicator)
{
<div class="app-progress-indicator"></div>
}
} }
</ChildContent> }
</ErrorBoundary> }
else
{
@if (!string.IsNullOrEmpty(_error))
{
<ModuleMessage Message="@_error" Type="@MessageType.Error"/>
}
}
@code { @code {
private string _message; private string _message;
private MessageType _messageType; private string _error;
private bool _progressIndicator = false; private MessageType _messageType;
private bool _progressIndicator = false;
private Type ModuleType { get; set; } private Type ModuleType { get; set; }
private IDictionary<string, object> ModuleParameters { get; set; } private IDictionary<string, object> ModuleParameters { get; set; }
[CascadingParameter] [CascadingParameter]
protected PageState PageState { get; set; } protected PageState PageState { get; set; }
[CascadingParameter] [CascadingParameter]
private Module ModuleState { get; set; } private Module ModuleState { get; set; }
private ModuleMessage ModuleMessage { get; set; } private ModuleMessage ModuleMessage { get; set; }
private RenderFragment DynamicComponent { get; set; } protected override void OnParametersSet()
{
_message = "";
if (!string.IsNullOrEmpty(ModuleState.ModuleType))
{
ModuleType = Type.GetType(ModuleState.ModuleType);
if (ModuleType != null)
{
ModuleParameters = new Dictionary<string, object> { { "ModuleInstance", this } };
return;
}
// module does not exist with typename specified
_message = string.Format(Localizer["Error.Module.InvalidName"], Utilities.GetTypeNameLastSegment(ModuleState.ModuleType, 0));
_messageType = MessageType.Error;
}
else
{
_message = string.Format(Localizer["Error.Module.InvalidType"], ModuleState.ModuleDefinitionName);
_messageType = MessageType.Error;
}
}
protected override void OnParametersSet() public void AddModuleMessage(string message, MessageType type)
{ {
_message = ""; _message = message;
if (!string.IsNullOrEmpty(ModuleState.ModuleType)) _messageType = type;
{ _progressIndicator = false;
ModuleType = Type.GetType(ModuleState.ModuleType); StateHasChanged();
if (ModuleType != null) }
{
ModuleParameters = new Dictionary<string, object> { { "ModuleInstance", this } };
return;
}
// module does not exist with typename specified
_message = string.Format(Localizer["Error.Module.InvalidName"], Utilities.GetTypeNameLastSegment(ModuleState.ModuleType, 0));
_messageType = MessageType.Error;
}
else
{
_message = string.Format(Localizer["Error.Module.InvalidType"], ModuleState.ModuleDefinitionName);
_messageType = MessageType.Error;
}
}
public void AddModuleMessage(string message, MessageType type) public void ShowProgressIndicator()
{ {
_message = message; _progressIndicator = true;
_messageType = type; StateHasChanged();
_progressIndicator = false; }
StateHasChanged();
}
public void ShowProgressIndicator() public void HideProgressIndicator()
{ {
_progressIndicator = true; _progressIndicator = false;
StateHasChanged(); StateHasChanged();
} }
public void HideProgressIndicator() protected override async Task OnErrorAsync(Exception exception)
{ {
_progressIndicator = false; // retrieve friendly localized error
StateHasChanged(); _error = Localizer["Error.Module.Exception"];
} // log error
int? userId = (PageState.User != null) ? PageState.User.UserId : null;
string category = GetType().AssemblyQualifiedName;
string feature = Utilities.GetTypeNameLastSegment(category, 1);
await LoggingService.Log(null, ModuleState.PageId, ModuleState.ModuleId, userId, category, feature, LogFunction.Other, LogLevel.Error, exception, "An Unexpected Error Has Occurred In {ModuleDefinitionName}: {Error}", ModuleState.ModuleDefinitionName, exception.Message);
await base.OnErrorAsync(exception);
return;
}
public new void Recover()
private string ErrorMessage(Exception context) {
{ _error = "";
var message = string.Format(Localizer["Error.Module.Exception"], ModuleState.ModuleDefinitionName); base.Recover();
if (UserSecurity.IsAuthorized(PageState.User, RoleNames.Host))
{
return $"{message}<br />{context}";
}
return message;
} }
} }