【发布时间】:2020-05-14 08:40:58
【问题描述】:
我想控制我的 Web 应用程序中发生的所有异常的详细信息。我想将自定义数据添加到异常中。如果处于调试模式,我还想添加更多信息。我确实想将此作为 JSON 格式传递给用户。
为此,我想使用自定义错误代码引发异常,并传递内部异常以进行调试。
在我的 startup.cs 中:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseMiddleware(typeof(ErrorHandlingMiddleware)); // Error handling middlware
....
在我的服务中,我抛出了一个异常:
catch (Exception e)
{
throw new Exception("E18", e.InnerException);
}
当我调试它时。我可以看到 e.InnerException 充满了数据。
魔法来了……嗯……有点。这是中间件:
public class ErrorHandlingMiddleware
{
static Dictionary<string, APIMessageDetails> responseMessageCodes = new Dictionary<string, APIMessageDetails>
{
...
{"E18", new APIMessageDetails {responseMessage = "An unknown error occured.", httpStatusCode = StatusCodes.Status500InternalServerError}},
...
}
private readonly RequestDelegate next;
public ErrorHandlingMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context)
{
try {
await next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private static Task HandleExceptionAsync(HttpContext context, Exception ex)
{
string errorCode = ex.Message;
APIMessageDetails result;
APIMessage apiMessage = new APIMessage();
if (errorCode != null)
{
if (responseMessageCodes.TryGetValue(errorCode, out result))
{
apiMessage.responseMessageCode = errorCode;
apiMessage.messageDetails = result;
#if DEBUG
apiMessage.messageDetails.exception = ex;
#endif
}
}
var jsonResult = JsonConvert.SerializeObject(apiMessage);
context.Response.ContentType = "application/json";
context.Response.StatusCode = apiMessage.messageDetails.httpStatusCode;
return context.Response.WriteAsync(jsonResult);
}
}
当我调试时,我可以看到中间件中捕获的异常确实包含 E18,但 innerException 为 null。我不明白为什么会这样;它被传递给抛出的异常......
希望有人能帮帮我。
【问题讨论】:
-
嗨。请为您的服务设置断点并检查 e 的 InnerException(在您的服务代码中)是否为空?如果e.InnerException为null,这种情况是正常的))
-
e.InnerException 已填充:e.InnerException = {"无法建立连接,因为目标机器主动拒绝了它。"}。在我的中间件中,ex.InnerException 始终为 null...
标签: c# exception .net-core middleware