Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merge to Live #29689

Merged
merged 3 commits into from
Jun 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion aspnetcore/fundamentals/error-handling.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ description: Discover how to handle errors in ASP.NET Core apps.
monikerRange: '>= aspnetcore-3.1'
ms.author: riande
ms.custom: mvc
ms.date: 01/18/2023
ms.date: 06/30/2023
uid: fundamentals/error-handling
---
# Handle errors in ASP.NET Core
Expand Down Expand Up @@ -91,6 +91,30 @@ The following code uses a lambda for exception handling:
> [!WARNING]
> Do **not** serve sensitive error information to clients. Serving errors is a security risk.

## IExceptionHandler

[IExceptionHandler](https://source.dot.net/#Microsoft.AspNetCore.Diagnostics/ExceptionHandler/IExceptionHandler.cs,adae2915ad0c6dc5) is an interface that gives the developer a callback for handling known exceptions in a central location.

`IExceptionHandler` implementations are registered by calling [`IServiceCollection.AddExceptionHandler<T>`](https://source.dot.net/#Microsoft.AspNetCore.Diagnostics/ExceptionHandler/ExceptionHandlerServiceCollectionExtensions.cs,e74aac24e3e2cbc9). Multiple implementations can be added, and they're called in the order registered. If an exception handler handles a request, it can return `true` to stop processing. If an exception isn't handled by any exception handler, then control falls back to the default behavior and options from the middleware. Different metrics and logs are emitted for handled versus unhandled exceptions.

The following example shows an `IExceptionHandler` implementation:

:::code language="csharp" source="~/fundamentals/error-handling/samples/8.x/ErrorHandlingSample/CustomExceptionHandler.cs":::

The following example shows how to register an `IExceptionHandler` implementation for dependency injection:

:::code language="csharp" source="~/fundamentals/error-handling/samples/8.x/ErrorHandlingSample/Program.cs" id="snippet_RegisterIExceptionHandler" highlight="7":::

When the preceding code runs in the Development environment:

* The `CustomExceptionHandler` is called first to handle an exception.
* After logging the exception, the `TryHandleException` method returns `false`, so the [developer exception page](#developer-exception-page) is shown.

In other environments:

* The `CustomExceptionHandler` is called first to handle an exception.
* After logging the exception, the `TryHandleException` method returns `false`, so the [`/Error` page](#exception-handler-page) is shown.

<!-- links to this in other docs require sestatuscodepages -->
<a name="sestatuscodepages"></a>

Expand Down
Original file line number Diff line number Diff line change
@@ -1,19 +1,25 @@
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Diagnostics;

namespace ErrorHandlingSample
{
public class CustomExceptionHandler : IExceptionHandler
{
private ILogger<CustomExceptionHandler> logger;
public CustomExceptionHandler(ILogger<CustomExceptionHandler> logger){
private readonly ILogger<CustomExceptionHandler> logger;
public CustomExceptionHandler(ILogger<CustomExceptionHandler> logger)
{
this.logger = logger;
}
public ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken)
public ValueTask<bool> TryHandleAsync(
HttpContext httpContext,
Exception exception,
CancellationToken cancellationToken)
{
var exceptionMessage = exception.Message;
logger.LogError("Error Message: {exceptionMessage}", exceptionMessage);
logger.LogError("Time of occurrence {time}", DateTime.Now);
// returned false to continue with the default behavior
logger.LogError(
"Error Message: {exceptionMessage}, Time of occurrence {time}",
exceptionMessage, DateTime.UtcNow);
// Return false to continue with the default behavior
// - or - return true to signal that this exception is handled
return ValueTask.FromResult(false);
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
// <snippet_AddDatabaseDeveloperPageExceptionFilter>
// <snippet_RegisterIExceptionHandler>
using ErrorHandlingSample;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddRazorPages();
builder.Services.AddExceptionHandler<CustomExceptionHandler>();
// </snippet_AddDatabaseDeveloperPageExceptionFilter>

// <snippet_UseExceptionHandler>
var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
// </snippet_UseExceptionHandler>

// Remaining Program.cs code omitted for brevity
// </snippet_RegisterIExceptionHandler>

app.UseHttpsRedirection();
app.UseStaticFiles();
Expand Down
10 changes: 9 additions & 1 deletion aspnetcore/release-notes/aspnetcore-8.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ author: rick-anderson
description: Learn about the new features in ASP.NET Core 8.0.
ms.author: riande
ms.custom: mvc
ms.date: 06/27/2023
ms.date: 06/30/2023
uid: aspnetcore-8
---
# What's new in ASP.NET Core 8.0
Expand Down Expand Up @@ -468,6 +468,14 @@ Metrics offers a number of improvements compared to existing event counters:

Metrics have been added for ASP.NET Core hosting, Kestrel, and SignalR. For more information, see [System.Diagnostics.Metrics](/dotnet/core/diagnostics/compare-metric-apis#systemdiagnosticsmetrics).

### IExceptionHandler

[IExceptionHandler](https://source.dot.net/#Microsoft.AspNetCore.Diagnostics/ExceptionHandler/IExceptionHandler.cs,adae2915ad0c6dc5) is a new interface that gives the developer a callback for handling known exceptions in a central location.

`IExceptionHandler` implementations are registered by calling [`IServiceCollection.AddExceptionHandler<T>`](https://source.dot.net/#Microsoft.AspNetCore.Diagnostics/ExceptionHandler/ExceptionHandlerServiceCollectionExtensions.cs,e74aac24e3e2cbc9). Multiple implementations can be added, and they're called in the order registered. If an exception handler handles a request, it can return `true` to stop processing. If an exception isn't handled by any exception handler, then control falls back to the default behavior and options from the middleware.

For more information, see [IExceptionHandler](xref:fundamentals/error-handling#iexceptionhandler).

<!--
## API controllers

Expand Down
2 changes: 1 addition & 1 deletion aspnetcore/tutorials/razor-pages/search.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ Save the changes and test the filter.

## Search by genre

Update the Index page's `OnGetAsync` method with the following code:
Update the `Movies/Index.cshtml.cs` page `OnGetAsync` method with the following code:

[!code-csharp[](~/tutorials/razor-pages/razor-pages-start/sample/RazorPagesMovie80/Pages/Movies/Index.cshtml.cs?name=snippet_SearchGenre)]

Expand Down
Loading