【问题标题】:Problem displaying meaningful error message from AJAX call显示来自 AJAX 调用的有意义的错误消息时出现问题
【发布时间】:2020-06-29 03:32:05
【问题描述】:

我正在像这样从 AJAX 调用 Razor 页面处理程序:

$.ajax({
    url: '?handler=Delete',
    data: {
        id: $(this).data('id')
    }
})
.fail(function (e) {
    alert(e.responseText);
});

这是我的处理程序,用于测试发生异常时会发生什么:

public async System.Threading.Tasks.Task OnGetDelete(int id)
{
    throw new Exception("This is an exception.");
}

如果在我的处理程序中抛出异常,那么我想显示错误描述。问题是e.responseText 包含的信息比我想向用户显示的要多。它包括对异常的描述,以及堆栈跟踪、标头和许多其他内容。

在上面的示例中,我只想显示“这是一个例外。”。尝试解析来自e.responseText 的消息是我唯一的解决方案吗?这是其他人正在做的吗?

【问题讨论】:

    标签: javascript ajax asp.net-core razor-pages


    【解决方案1】:

    在上面的示例中,我只想显示“这是一个例外。”。

    要显示“This is an exception.”,可以使用以下代码 sn -p:

    .fail(function (e) {
        //console.log(e);
        var mes = e.responseText.split('\n')[0];
        alert(mes.substring(17, mes.length - 1));
    })
    

    测试结果:

    更新:

    如果可能,您可以尝试动态捕获该特定处理程序方法中发生的异常,然后生成您预期的响应,如下所示。

    app.Use(async (context, next) =>
    {
        try
        {
            await next();
        }
        catch (Exception ex)
        {
    
            if (context.Request.Path.StartsWithSegments("{request_path_here}") && context.Request.Query["handler"].Any())
            {
                if (context.Request.Query["handler"]== "Delete")
                {
                    context.Response.StatusCode = 500;
                    var result = System.Text.Json.JsonSerializer.Serialize(new { error = ex.Message });
                    context.Response.ContentType = "application/json";
                    await context.Response.WriteAsync(result);
                }
            }
        }
    });
    

    responseText 将是"{"error":"This is an exception."}",您可以使用JSON.parse(e.responseText).error 获取异常消息。

    测试结果:

    【讨论】:

    • 谢谢,但我的专长是解析文本。您的代码是关于错误文本的硬编码假设,我对此并不满意。无论如何,我的问题是我是否必须解析它,或者这些信息是否可以以更可预测的方式获得。
    • 嗨@JonathanWood,请检查我的更新。希望此解决方法可以帮助您实现要求。
    • 什么是app.Use()
    • 它可以帮助将定义的中间件委托添加到应用程序的请求管道中。您可以从here获取更多信息。
    猜你喜欢
    • 2012-07-24
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多