# ASP.NET Core: handling errors

> Displaying a custom error page in ASP.NET Core is very simple, but there are some pitfalls to avoid. To display an error page (error 500), simply write the…

- Author: Jérôme Giacomini
- Language: en
- Canonical URL: [ASP.NET Core: handling errors](https://jeromegiacomini.net/articles/2019/11/05/asp-net-core-handling-errors)
- Published: 2019-11-05
- Last modified: 2026-09-05
- Topics: ASP.NET Core, .NET, C#

Displaying a custom error page in ASP.NET Core is very simple, but there are some pitfalls to avoid.

To display an error page (error 500), simply write the following line of code:

```csharp

app.UseExceptionHandler("Error"); 
```


To view the other types of errors (page 404, etc.) simply call the following method:

```csharp

app.UseStatusCodePagesWithRedirects("/StatusCode?code={0}"); 
```


Unfortunately, I'm not sure. **this n’It's not that simple** !
If your ASP.NET Core website hosts WebAPIs they will also be affected by these changes

## Excludes APIs from custom error pages

In such cases, I am fortunate to be able to invoke [A wizard from ASP.NET Core](https://blogs.infinitesquare.com/users/touvre) In addition, I highly recommend his series of articles on the use of[User defined function with EF Core](https://blogs.infinitesquare.com/posts/divers/user-defined-functions-sql-server-entity-framework-usages-et-optimisations-partie-1).

### Change the management of the StatusCode

To change the display of the page managing the **StatusCode** so we have to go through a **StatusCodePagesOptions** And exclude all roads that start with api”.

```csharp

app.UseStatusCodePages(new StatusCodePagesOptions()
{
            HandleAsync = ctx =>
            {
                if (ctx.HttpContext.Request.Path != null &amp;&amp;
                !ctx.HttpContext.Request.Path.Value.StartsWith("api"))
                {
                    ctx.HttpContext.Response.Redirect($"/StatusCode?code={ctx.HttpContext.Response.StatusCode}");
                    return Task.CompletedTask;
                }

                return ctx.Next.Invoke(ctx.HttpContext);
            }
});
```


### Changes in error management

For error management we will use the same logic, all segments starting with api will be excluded.

**Please note:** that we use the method **UseWhen** This means that middleware can only be used in certain cases.

```csharp

app.UseWhen(ctx => !ctx.Request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase), cfg =>
                 cfg.UseExceptionHandler("/Error")
```


Happy coding 🙂

## To go further:
- [Link to the official ASP.NET Core documentation](https://docs.microsoft.com/fr-fr/aspnet/core/fundamentals/error-handling)
