Skip to content
Merged
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
36 changes: 33 additions & 3 deletions src/Game.Server/Middleware/ExceptionHandlingMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,16 @@ public class ExceptionHandlingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<ExceptionHandlingMiddleware> _logger;
private readonly bool _isDevelopment;

public ExceptionHandlingMiddleware(RequestDelegate next, ILogger<ExceptionHandlingMiddleware> logger)
public ExceptionHandlingMiddleware(
RequestDelegate next,
ILogger<ExceptionHandlingMiddleware> logger,
IHostEnvironment environment)
{
_next = next;
_logger = logger;
_isDevelopment = environment.IsDevelopment();
}

public async Task InvokeAsync(HttpContext context)
Expand All @@ -28,7 +33,7 @@ public async Task InvokeAsync(HttpContext context)
}
}

private static Task HandleExceptionAsync(HttpContext context, Exception exception)
private Task HandleExceptionAsync(HttpContext context, Exception exception)
{
var (statusCode, errorCode) = exception switch
{
Expand All @@ -43,7 +48,7 @@ private static Task HandleExceptionAsync(HttpContext context, Exception exceptio
var response = new ApiErrorResponse
{
Error = errorCode,
Message = exception.Message,
Message = GetErrorMessage(exception, errorCode),
TraceId = context.TraceIdentifier,
};

Expand All @@ -60,4 +65,29 @@ private static Task HandleExceptionAsync(HttpContext context, Exception exceptio
context.Response.ContentType = "application/json";
return context.Response.WriteAsJsonAsync(response);
}

private string GetErrorMessage(Exception exception, string errorCode)
{
// ErrorException は開発者が制御したメッセージなので常に返す
if (exception is ErrorException)
{
return exception.Message;
}

// 開発環境では詳細メッセージを返す
if (_isDevelopment)
{
return exception.Message;
}

// 本番環境ではエラーコードに対応する汎用メッセージを返す
return errorCode switch
{
"BAD_REQUEST" => "The request was invalid.",
"UNAUTHORIZED" => "Authentication is required.",
"NOT_FOUND" => "The requested resource was not found.",
"CONFLICT" => "The request conflicts with the current state.",
_ => "An internal error occurred.",
};
}
}
Loading