异常输出

This commit is contained in:
陈国伟 2021-07-16 16:05:22 +08:00
parent c96dab0df8
commit c3fefdf4d3
4 changed files with 62 additions and 18 deletions

View File

@ -30,13 +30,25 @@ namespace FastGithub
if (options.CurrentValue.IsMatch(host) == false)
{
await context.Response.WriteAsJsonAsync(new { message = $"不支持以{host}访问" });
return;
}
else
{
var port = context.Request.Host.Port ?? 443;
var destinationPrefix = $"https://{host}:{port}/";
var httpClient = new HttpMessageInvoker(httpClientHanlder, disposeHandler: false);
await httpForwarder.SendAsync(context, destinationPrefix, httpClient);
var error = await httpForwarder.SendAsync(context, destinationPrefix, httpClient);
if (error != ForwarderError.None)
{
var errorFeature = context.GetForwarderErrorFeature();
if (errorFeature != null)
{
await context.Response.WriteAsJsonAsync(new
{
error = error.ToString(),
message = errorFeature.Exception?.Message
});
}
}
});

View File

@ -0,0 +1,20 @@
using System;
namespace FastGithub.ReverseProxy
{
/// <summary>
/// 反向代理异常
/// </summary>
sealed class ReverseProxyException : Exception
{
/// <summary>
/// 反向代理异常
/// </summary>
/// <param name="message"></param>
/// <param name="inner"></param>
public ReverseProxyException(string message, Exception? inner)
: base(message, inner)
{
}
}
}

View File

@ -5,7 +5,6 @@ using Microsoft.Extensions.Options;
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
@ -44,23 +43,36 @@ namespace FastGithub.ReverseProxy
{
// 缓存以避免做不必要的并发查询
var key = $"domain:{domain}";
var address = await this.memoryCache.GetOrCreateAsync(key, async e =>
var address = await this.memoryCache.GetOrCreateAsync(key, e =>
{
e.SetAbsoluteExpiration(this.cacheTimeSpan);
var dnsClient = new DnsClient(this.options.CurrentValue.TrustedDns.ToIPEndPoint());
var addresses = await dnsClient.Lookup(domain, DNS.Protocol.RecordType.A, cancellationToken);
return addresses?.FirstOrDefault();
return this.LookupAsync(domain, cancellationToken);
});
if (address == null)
{
var message = $"无法解析{domain}的ip";
this.logger.LogWarning(message);
throw new HttpRequestException(message);
}
this.logger.LogInformation($"[{address}->{domain}]");
return address;
}
/// <summary>
/// 查找ip
/// </summary>
/// <param name="domain"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private async Task<IPAddress> LookupAsync(string domain, CancellationToken cancellationToken)
{
var endpoint = this.options.CurrentValue.TrustedDns.ToIPEndPoint();
try
{
var dnsClient = new DnsClient(endpoint);
var addresses = await dnsClient.Lookup(domain, DNS.Protocol.RecordType.A, cancellationToken);
var address = addresses?.FirstOrDefault();
return address ?? throw new Exception($"解析不到{domain}的ip");
}
catch (Exception ex)
{
throw new ReverseProxyException($"dns({endpoint}){ex.Message}", ex);
}
}
}
}