Skip to content

Commit 2da64b0

Browse files
Answer storefront errors with 500 instead of a redirect to the error page (#1175)
1 parent ea63ebd commit 2da64b0

4 files changed

Lines changed: 265 additions & 64 deletions

File tree

Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
using Grand.Data;
2+
using Grand.Web.Common.Infrastructure;
3+
using Microsoft.AspNetCore.Hosting;
4+
using Microsoft.AspNetCore.Http;
5+
using Microsoft.AspNetCore.Http.Features;
6+
using Microsoft.Extensions.DependencyInjection;
7+
using Microsoft.Extensions.FileProviders;
8+
using Microsoft.Extensions.Logging.Abstractions;
9+
using Microsoft.Net.Http.Headers;
10+
using Microsoft.VisualStudio.TestTools.UnitTesting;
11+
using MongoDB.Driver;
12+
using MongoDB.Driver.Core.Clusters;
13+
using MongoDB.Driver.Core.Connections;
14+
using MongoDB.Driver.Core.Servers;
15+
using Moq;
16+
using System.Net;
17+
18+
namespace Grand.Web.Common.Tests.Infrastructure;
19+
20+
[TestClass]
21+
public class GrandExceptionHandlerTests
22+
{
23+
private GrandExceptionHandler _handler = null!;
24+
private string _webRoot = null!;
25+
26+
[TestInitialize]
27+
public void Init()
28+
{
29+
DataSettingsManager.Initialize(Path.Join(Path.GetTempPath(), "grand-exception-handler-tests-settings.json"));
30+
DataSettingsManager.Instance.LoadDataSettings(new DataSettings { ConnectionString = "mongodb://localhost" });
31+
32+
_webRoot = Path.Combine(Path.GetTempPath(), "errorpage-" + Guid.NewGuid().ToString("N"));
33+
Directory.CreateDirectory(_webRoot);
34+
File.WriteAllText(Path.Combine(_webRoot, "errorpage.htm"), "<h1>INTERNAL ERROR</h1>");
35+
36+
_handler = new GrandExceptionHandler(NullLogger<GrandExceptionHandler>.Instance);
37+
}
38+
39+
[TestCleanup]
40+
public void Cleanup()
41+
{
42+
Directory.Delete(_webRoot, true);
43+
}
44+
45+
private HttpContext CreateContext()
46+
{
47+
var env = new Mock<IWebHostEnvironment>();
48+
env.SetupProperty(e => e.WebRootFileProvider, new PhysicalFileProvider(_webRoot));
49+
var services = new ServiceCollection();
50+
services.AddSingleton(env.Object);
51+
52+
var context = new DefaultHttpContext { RequestServices = services.BuildServiceProvider() };
53+
context.Request.Path = "/category";
54+
context.Response.Body = new MemoryStream();
55+
return context;
56+
}
57+
58+
private static string ReadBody(HttpContext context)
59+
{
60+
context.Response.Body.Position = 0;
61+
return new StreamReader(context.Response.Body).ReadToEnd();
62+
}
63+
64+
[TestMethod]
65+
public async Task TryHandleAsync_WebRequest_Writes500WithStaticErrorPage()
66+
{
67+
var context = CreateContext();
68+
69+
var handled = await _handler.TryHandleAsync(context, new InvalidOperationException(), CancellationToken.None);
70+
71+
Assert.IsTrue(handled);
72+
Assert.AreEqual(StatusCodes.Status500InternalServerError, context.Response.StatusCode);
73+
Assert.AreEqual("no-store", context.Response.Headers[HeaderNames.CacheControl].ToString());
74+
Assert.IsFalse(context.Response.Headers.ContainsKey(HeaderNames.Location));
75+
Assert.IsFalse(context.Response.Headers.ContainsKey(HeaderNames.RetryAfter));
76+
StringAssert.StartsWith(context.Response.ContentType, "text/html");
77+
Assert.AreEqual("<h1>INTERNAL ERROR</h1>", ReadBody(context));
78+
}
79+
80+
[TestMethod]
81+
public async Task TryHandleAsync_MongoServerSelectionTimeout_Writes503WithRetryAfter()
82+
{
83+
var context = CreateContext();
84+
85+
var handled = await _handler.TryHandleAsync(context, new TimeoutException("server selection"), CancellationToken.None);
86+
87+
Assert.IsTrue(handled);
88+
Assert.AreEqual(StatusCodes.Status503ServiceUnavailable, context.Response.StatusCode);
89+
Assert.AreEqual("30", context.Response.Headers[HeaderNames.RetryAfter].ToString());
90+
Assert.AreEqual("<h1>INTERNAL ERROR</h1>", ReadBody(context));
91+
}
92+
93+
[TestMethod]
94+
public async Task TryHandleAsync_MongoConnectionException_Writes503()
95+
{
96+
var context = CreateContext();
97+
var connectionId = new ConnectionId(new ServerId(new ClusterId(), new DnsEndPoint("localhost", 27017)));
98+
99+
await _handler.TryHandleAsync(context, new MongoConnectionException(connectionId, "refused"), CancellationToken.None);
100+
101+
Assert.AreEqual(StatusCodes.Status503ServiceUnavailable, context.Response.StatusCode);
102+
}
103+
104+
[TestMethod]
105+
public async Task TryHandleAsync_ApiRequest_WritesProblemDetails500()
106+
{
107+
var context = CreateContext();
108+
context.Request.Headers[HeaderNames.Authorization] = "Bearer token";
109+
110+
var handled = await _handler.TryHandleAsync(context, new TimeoutException(), CancellationToken.None);
111+
112+
Assert.IsTrue(handled);
113+
Assert.AreEqual(StatusCodes.Status500InternalServerError, context.Response.StatusCode);
114+
Assert.IsFalse(context.Response.Headers.ContainsKey(HeaderNames.RetryAfter));
115+
StringAssert.Contains(ReadBody(context), "An error occurred while processing your request");
116+
}
117+
118+
[TestMethod]
119+
public async Task TryHandleAsync_ResponseStarted_ReturnsFalse()
120+
{
121+
var context = CreateContext();
122+
var responseFeature = new Mock<IHttpResponseFeature>();
123+
responseFeature.Setup(f => f.HasStarted).Returns(true);
124+
context.Features.Set(responseFeature.Object);
125+
126+
var handled = await _handler.TryHandleAsync(context, new InvalidOperationException(), CancellationToken.None);
127+
128+
Assert.IsFalse(handled);
129+
}
130+
}

‎src/Web/Grand.Web.Common/Infrastructure/GrandExceptionHandler.cs‎

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,20 @@
11
using Grand.Data;
22
using Microsoft.AspNetCore.Diagnostics;
3+
using Microsoft.AspNetCore.Hosting;
34
using Microsoft.AspNetCore.Http;
45
using Microsoft.AspNetCore.Mvc;
56
using Microsoft.Extensions.DependencyInjection;
67
using Microsoft.Extensions.Logging;
8+
using Microsoft.Net.Http.Headers;
9+
using MongoDB.Driver;
710

811
namespace Grand.Web.Common.Infrastructure;
912

1013
/// <summary>
1114
/// Handles unhandled exceptions according to ASP.NET Core best practices.
1215
/// For API requests (Bearer token) it writes an RFC 7807 ProblemDetails JSON response.
13-
/// For regular web (Razor/MVC) requests it redirects to the static error page (/errorpage.htm).
16+
/// For regular web (Razor/MVC) requests it writes the static error page (wwwroot/errorpage.htm) with status 500,
17+
/// or 503 with Retry-After when the database could not be reached.
1418
/// </summary>
1519
public class GrandExceptionHandler : IExceptionHandler
1620
{
@@ -35,10 +39,23 @@ public async ValueTask<bool> TryHandleAsync(
3539

3640
if (!ApplicationBuilderExtensions.IsApiRequest(httpContext.Request))
3741
{
38-
// For Razor/MVC web requests, redirect to the static error page so the
39-
// browser always sees a user-friendly page (the path-based re-execution
40-
// fallback in UseExceptionHandler is unreliable in an MVC pipeline).
41-
httpContext.Response.Redirect("/errorpage.htm", permanent: false);
42+
// Write the static error page directly (no MVC, no database) so it works while MongoDB is down
43+
// and the failure stays visible as a 5xx to metrics and load balancers.
44+
var unavailable = exception is MongoConnectionException or TimeoutException;
45+
httpContext.Response.StatusCode = unavailable
46+
? StatusCodes.Status503ServiceUnavailable
47+
: StatusCodes.Status500InternalServerError;
48+
if (unavailable)
49+
httpContext.Response.Headers[HeaderNames.RetryAfter] = "30";
50+
httpContext.Response.Headers[HeaderNames.CacheControl] = "no-store";
51+
httpContext.Response.ContentType = "text/html; charset=utf-8";
52+
53+
var errorPage = httpContext.RequestServices.GetService<IWebHostEnvironment>()?
54+
.WebRootFileProvider.GetFileInfo("errorpage.htm");
55+
if (errorPage is { Exists: true })
56+
await httpContext.Response.SendFileAsync(errorPage, cancellationToken);
57+
else
58+
await httpContext.Response.WriteAsync("An error occurred while processing your request.", cancellationToken);
4259
return true;
4360
}
4461

‎src/Web/Grand.Web/wwwroot/assets/errorpage/error.css‎

Lines changed: 0 additions & 28 deletions
This file was deleted.
Lines changed: 113 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,119 @@
1-
<!DOCTYPE html>
2-
<html>
1+
<!DOCTYPE html>
2+
<html lang="en">
33
<head>
4-
<title>Error</title>
4+
<meta charset="utf-8">
55
<meta name="viewport" content="width=device-width, initial-scale=1">
6-
<meta http-equiv="Content-type" content="text/html;charset=UTF-8"/>
7-
<link href="/assets/errorpage/error.css" rel="stylesheet">
6+
<meta name="robots" content="noindex">
7+
<title>Something went wrong</title>
8+
<style>
9+
:root {
10+
--bg: #f6f7f9;
11+
--card: #ffffff;
12+
--text: #1f2328;
13+
--muted: #59636e;
14+
--border: #e3e6ea;
15+
--accent: #2563eb;
16+
--accent-text: #ffffff;
17+
--icon-bg: #fdecec;
18+
--icon: #d1242f;
19+
}
20+
@media (prefers-color-scheme: dark) {
21+
:root {
22+
--bg: #0f1216;
23+
--card: #171b21;
24+
--text: #e6e8eb;
25+
--muted: #9aa4af;
26+
--border: #2a3038;
27+
--accent: #4c8dff;
28+
--accent-text: #0f1216;
29+
--icon-bg: #3a1d20;
30+
--icon: #ff7b72;
31+
}
32+
}
33+
* { box-sizing: border-box; }
34+
html, body { height: 100%; }
35+
body {
36+
margin: 0;
37+
display: flex;
38+
align-items: center;
39+
justify-content: center;
40+
padding: 16px;
41+
background: var(--bg);
42+
color: var(--text);
43+
font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
44+
line-height: 1.5;
45+
}
46+
main {
47+
width: 100%;
48+
max-width: 480px;
49+
padding: 40px 32px;
50+
background: var(--card);
51+
border: 1px solid var(--border);
52+
border-radius: 16px;
53+
box-shadow: 0 8px 24px rgba(0, 0, 0, .06);
54+
text-align: center;
55+
}
56+
.icon {
57+
display: inline-flex;
58+
align-items: center;
59+
justify-content: center;
60+
width: 64px;
61+
height: 64px;
62+
margin-bottom: 20px;
63+
border-radius: 50%;
64+
background: var(--icon-bg);
65+
color: var(--icon);
66+
}
67+
h1 {
68+
margin: 0 0 12px;
69+
font-size: 24px;
70+
font-weight: 600;
71+
}
72+
p {
73+
margin: 0 0 8px;
74+
color: var(--muted);
75+
}
76+
.actions {
77+
display: flex;
78+
flex-wrap: wrap;
79+
gap: 12px;
80+
justify-content: center;
81+
margin-top: 28px;
82+
}
83+
.button {
84+
display: inline-block;
85+
padding: 10px 20px;
86+
border: 1px solid var(--border);
87+
border-radius: 8px;
88+
color: var(--text);
89+
font-weight: 500;
90+
text-decoration: none;
91+
}
92+
.button:hover { border-color: var(--muted); }
93+
.button.primary {
94+
background: var(--accent);
95+
border-color: var(--accent);
96+
color: var(--accent-text);
97+
}
98+
.button.primary:hover { opacity: .9; }
99+
</style>
8100
</head>
9101
<body>
10-
<div class="container">
11-
<div class="error-card">
12-
<h1>INTERNAL ERROR</h1>
13-
<h2>We're sorry, an internal error occurred.</h2>
14-
<div class="block">
15-
<blockquote>
16-
17-
<p>
18-
<strong>Our supporting staff has been notified of this error and will address the issue shortly.</strong>
19-
</p>
20-
<p>
21-
We apologize for the inconvenience.
22-
</p>
23-
<p>
24-
Please try clicking your browsers 'back' button or try reloading the home page.
25-
</p>
26-
<p>
27-
<br/>
28-
If you continue to receive this message, please try again in a little while.
29-
<br/>
30-
<br/>
31-
Thank you for your patience.
32-
</blockquote>
33-
</div>
102+
<main>
103+
<div class="icon" aria-hidden="true">
104+
<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
105+
<path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/>
106+
<line x1="12" y1="9" x2="12" y2="13"/>
107+
<line x1="12" y1="17" x2="12.01" y2="17"/>
108+
</svg>
34109
</div>
35-
</div>
110+
<h1>Something went wrong</h1>
111+
<p>We couldn't load this page right now. This is usually temporary.</p>
112+
<p>Please try again in a moment. If the problem continues, come back a little later.</p>
113+
<div class="actions">
114+
<a class="button primary" href="">Try again</a>
115+
<a class="button" href="/">Go to the home page</a>
116+
</div>
117+
</main>
36118
</body>
37-
</html>
119+
</html>

0 commit comments

Comments
 (0)