public class MyErrorBoundary : ErrorBoundary
{
public new Exception? CurrentException => base.CurrentException;
}
@code {
[Parameter(CaptureUnmatchedValues = true)]
public Dictionary<string, object> Attributes { get; set; }
[Parameter]
public RenderFragment ChildContent { get; set; }
private MyErrorBoundary boundary;
}
<div @attributes="Attributes">
<ExceptionBoundary @ref="boundary">
<ChildContent>
@ChildContent
</ChildContent>
<ErrorContent>
<ExceptionView Exception="@boundary.CurrentException"
HowToResume="(() => boundary.Recover())" />
</ErrorContent>
</ExceptionBoundary>
</div>
<ContainerWithExceptionHandling class="content px-4">
@Body
</ContainerWithExceptionHandling>
<ErrorBoundary>
<ChildContent>
@Body
</ChildContent>
<ErrorContent Context="Exception">
<div>
@Exception.Message<br/>
</div>
</ErrorContent>
</ErrorBoundary>
从错误内容的上下文(RenderFragment)中获取当前异常(请参见上面的代码示例)。
ErrorBoundaryBase ->
/// <summary>
/// The content to be displayed when there is an error.
/// </summary>
[Parameter] public RenderFragment<Exception>? ErrorContent { get; set; }
@Exception.InnerException
没有任何东西...没有堆栈跟踪数据。如果我在我的服务中抛出异常,我只能得到异常消息文本,没有任何指示异常发生在哪个方法/行。 - undefined@using Microsoft.Extensions.Logging
@inject ILogger<Error> Logger
@inject IJSRuntime jsRuntime
<CascadingValue Value="this">
@ChildContent
</CascadingValue>
@code {
[Parameter]
public RenderFragment? ChildContent { get; set; }
public void ProcessError(Exception ex)
{
Logger.LogError("Error:ProcessError - Type: {Type} Message: {Message}",
ex.GetType(), ex.Message);
jsRuntime.ToastrError("An Error has occured!");
//StateHasChanged();
}
}
“Error” 组件可以使用 Blazor 内置的日志记录器记录错误,并通过 “Toastr” 显示 JavaScript 错误消息,方法是通过 “ProcessError” 方法。显然,其他日志记录器,如 Serilog、Elmah 甚至其他自定义日志记录器都可以在此方法中使用。<Error>
<Router ...>
...
</Router>
</Error>
@code {
[CascadingParameter]
public Error? Error { get; set; }
private void CreatePost()
{
try
{
throw new InvalidOperationException("a message!");
}
catch (Exception ex)
{
Error?.ProcessError(ex);
}
}
}
CascadingParameter
,并且在 try catch 块中调用了 Error 组件的 ProcessError
方法,并将发生的异常发送给它。在我的示例中,Error 组件只有一个错误处理方法。显然,该组件可以具有多个其他自定义错误处理方法,以用于不同的目的。ErrorBoundary.OnErrorAsync
也可以实现相同的功能。 - AlexErrorBoundary.OnErrorAsync
也可以实现相同的效果。 - undefined
CurrentException
。或者我对这个问题有误解吗? - Avrohom Yisroel@ref
来获取CurrentException,从而获取到MyErrorBoundary组件。我已经编辑了我的原始答案,为你说明了这一点。 - Aulimaitar@ref
来获取CurrentException,以获取MyErrorBoundary组件的引用。我已经编辑了我的原始答案,为你说明了这一点。 - undefined