C# .Net自定义异常无法被React Axios识别及状态码不符问题排查
问题原因分析
后端问题
Minimal API 默认未处理自定义异常
Minimal API 不会自动识别并处理自定义异常类型(如RestServerException),当未配置异常处理逻辑时,框架会将所有未捕获的异常统一转换为500 Internal Server Error响应,忽略你自定义的HTTP状态码和错误信息。异常处理逻辑缺失
当前代码仅抛出RestServerException,但没有对应的中间件或端点内的捕获逻辑,导致框架无法将异常映射为你期望的HTTP响应。
前端问题
- Axios错误处理不完整
当前getUser方法的catch块仅打印错误,没有将错误向上传递,导致上层then仍会执行,且拿到的res2为undefined,无法识别自定义异常。 - 未正确读取错误响应内容
Axios捕获的错误中,自定义错误信息存储在err.response.data中,当前代码未提取这部分内容,导致无法获取后端返回的自定义错误码和描述。
解决方法
后端修复
方案1:添加全局异常处理中间件
在Program.cs中注册全局异常处理中间件,专门捕获RestServerException并返回自定义响应:
app.UseExceptionHandler(errorApp => { errorApp.Run(async context => { var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>(); var exception = exceptionHandlerPathFeature?.Error; if (exception is RestServerException restEx) { context.Response.StatusCode = (int)restEx.HttpStatusCode; context.Response.ContentType = "application/json"; var errorResponse = new { restEx.Message, restEx.ErrorDescription.ErrorCode, restEx.ErrorDescription.Property }; await context.Response.WriteAsJsonAsync(errorResponse); } else { // 处理其他异常,返回默认500 context.Response.StatusCode = StatusCodes.Status500InternalServerError; await context.Response.WriteAsJsonAsync(new { Message = "服务器内部错误" }); } }); });
确保RestServerException类暴露HttpStatusCode、Message、ErrorDescription等可访问的属性。
方案2:端点内手动捕获异常
如果不想全局处理,可以在Minimal API端点中直接包裹业务逻辑:
app.MapPost("v/1/signumid_integrations/user", async (ExchangeOBORequest request) => { try { return Results.Ok(await IntegrationsService.GetUser(request)); } catch (RestServerException ex) { return Results.Problem( detail: ex.Message, statusCode: (int)ex.HttpStatusCode, extensions: new Dictionary<string, object> { { "errorCode", ex.ErrorDescription.ErrorCode }, { "property", ex.ErrorDescription.Property } }); } });
前端修复
修改Axios请求的错误处理逻辑,传递错误并提取自定义信息:
getUser(request: any) { return axios .post<any, AxiosResponse<any>>("https://localhost:5002/v/1/signumid_integrations/user", request) .then((res) => { console.log(res); return res.data; }) .catch(function (err) { // 提取后端返回的自定义错误信息 const errorInfo = err.response?.data; console.error("请求错误:", errorInfo || err.message); // 重新抛出错误,让上层能捕获 return Promise.reject(errorInfo || err); }); }
修改调用逻辑,处理错误情况:
httpClient .getUser(request) .then((res2) => { initiator.current = res2.mail === null || res2.mail === undefined || res2.mail === "" ? res2.userPrincipalName : res2.mail; }) .catch((err) => { // 这里处理自定义异常,比如提示用户 console.error("获取用户失败:", err.errorCode, err.Message); // 可添加UI提示逻辑 });
内容的提问来源于stack exchange,提问作者MatejDodevski
相关产品推荐
相关产品推荐

