如何通过jQuery.ajax获取ASP.NET后端的Exception异常信息?
解决方法
后端调整方案
方案1:返回结构化错误响应(推荐)
不要直接抛出Exception,而是返回带有错误信息的ActionResult,让后端输出JSON格式的错误数据,方便前端解析:
ASP.NET Core写法:
if (appointmentScheduledStartDate.HasValue) { var appointmentDate = appointmentScheduledStartDate.Value.Date.AddDays(1); if(appointmentDate < currentDateAndTime) { // 返回400错误+自定义信息 return BadRequest(new { Message = "Link Expired" }); } } // 正常逻辑返回成功结果 return Ok();
ASP.NET MVC(非Core)写法:
if (appointmentScheduledStartDate.HasValue) { var appointmentDate = appointmentScheduledStartDate.Value.Date.AddDays(1); if(appointmentDate < currentDateAndTime) { return new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent( Newtonsoft.Json.JsonConvert.SerializeObject(new { Message = "Link Expired" }), Encoding.UTF8, "application/json") }; } }
方案2:全局异常统一处理
如果需要统一处理所有未捕获异常,可配置全局异常中间件(ASP.NET Core),自动将异常转为JSON格式输出:
// Program.cs 中添加配置 app.UseExceptionHandler(errorApp => { errorApp.Run(async context => { context.Response.StatusCode = StatusCodes.Status400BadRequest; context.Response.ContentType = "application/json"; var exceptionFeature = context.Features.Get<IExceptionHandlerPathFeature>(); var errorMsg = exceptionFeature?.Error.Message ?? "Unknown error"; await context.Response.WriteAsync(System.Text.Json.JsonSerializer.Serialize(new { Message = errorMsg })); }); });
配置后直接抛Exception,后端也会返回JSON格式的错误信息。
前端调整方案
修改error回调逻辑,先将响应文本解析为JSON对象,再读取错误信息:
function logChekInData(entityName, recordId, userId, lat, lon) { x.innerHTML = "Please wait..."; $.ajax({ type: "POST", dataType: "Json", contentType: "application/json; charset=utf-8", url: '@Url.Action("LogCheckIn", "InvestigatorCheckIn")', data: JSON.stringify({ 'entityName': entityName, "recordId": recordId, "userId": userId, "lat": lat, "lon": lon }), async: false, success: function (data) { x.innerHTML = "Successfully tracked your location."; }, error: function (xhr) { try { // 解析响应文本为JSON对象 var errorData = JSON.parse(xhr.responseText); x.innerHTML = errorData.Message || "Error occurred. Please try later."; } catch (e) { // 解析失败时显示通用错误 x.innerHTML = "Error occurred. Please try later."; } } }); }
原问题原因
之前直接抛Exception时,ASP.NET默认返回HTML格式的错误页面,而非JSON数据。此时xhr.responseText是一串HTML字符串,不是JSON对象,自然无法通过.Message获取属性,所以显示undefined。
内容的提问来源于stack exchange,提问作者Nayeem Rahman
相关产品推荐
相关产品推荐

