Improve URL config parsing and mail exception handling
Refactor Program.cs to robustly parse and validate URLs from config, logging a warning if none are valid. Enhance MailService exception handling to log full exceptions and avoid interrupting OTP generation by swallowing mail send errors.
This commit is contained in:
parent
2533b5298f
commit
2d603e4fc6
@ -33,13 +33,25 @@ Log.Logger = loggerConfiguration
|
|||||||
.WriteTo.File("logs/portblog.txt", rollingInterval: RollingInterval.Day)
|
.WriteTo.File("logs/portblog.txt", rollingInterval: RollingInterval.Day)
|
||||||
.CreateLogger();
|
.CreateLogger();
|
||||||
|
|
||||||
var urls = builder.Configuration.GetSection("Urls");
|
var urlsSection = builder.Configuration.GetSection("Urls");
|
||||||
|
var urlsValue = urlsSection.Value;
|
||||||
|
|
||||||
if (!string.IsNullOrEmpty(urls.Value))
|
if (!string.IsNullOrWhiteSpace(urlsValue))
|
||||||
{
|
{
|
||||||
var allowedUrlsToUse = urls.Value.Split(',');
|
var allowedUrlsToUse = urlsValue
|
||||||
|
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
|
||||||
|
.Where(u => Uri.IsWellFormedUriString(u, UriKind.Absolute))
|
||||||
|
.ToArray();
|
||||||
|
|
||||||
builder.WebHost.UseUrls(allowedUrlsToUse);
|
if (allowedUrlsToUse.Length > 0)
|
||||||
|
{
|
||||||
|
builder.WebHost.UseUrls(allowedUrlsToUse);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// optionally log or throw depending on desired behavior
|
||||||
|
Log.Warning("Configured 'Urls' section was present but no valid URLs were found.");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var allowedCorsOrigins = builder.Configuration.GetSection("AllowedCorsOrigins");
|
var allowedCorsOrigins = builder.Configuration.GetSection("AllowedCorsOrigins");
|
||||||
|
|||||||
@ -67,16 +67,14 @@ namespace PortBlog.API.Services
|
|||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
logger.LogCritical(
|
// Log full exception and persist failed message. Do not rethrow to avoid causing a 500 from OTP generation
|
||||||
"Exception while sending mail from {FromEmail} ({Name}): {Exception}",
|
logger.LogCritical(ex, "Exception while sending mail from {FromEmail} ({Name}).", messageSendDto.FromEmail, messageSendDto.Name);
|
||||||
messageSendDto.FromEmail,
|
|
||||||
messageSendDto.Name,
|
|
||||||
ex.Message
|
|
||||||
);
|
|
||||||
messageSendDto.SentStatus = (int)MailConstants.MailStatus.Failed;
|
messageSendDto.SentStatus = (int)MailConstants.MailStatus.Failed;
|
||||||
mailRepository.AddMessage(messageEntity);
|
mailRepository.AddMessage(messageEntity);
|
||||||
await mailRepository.SaveChangesAsync();
|
await mailRepository.SaveChangesAsync();
|
||||||
throw new Exception();
|
|
||||||
|
// swallow the exception so OTP generation continues; caller can inspect delivery status via message logs
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user