Azure B2C自定义策略:如何捕获系统异常信息并发送至REST API?
如何捕获指定异常消息并发送到自定义REST API
完全可以实现捕获该异常消息并发送到你的REST API,分两种场景给出具体方案:
一、在应用代码中直接捕获(推荐)
在处理用户登录的逻辑里,直接拦截认证失败的异常或结果,提取消息并调用API,同时记录用户输入的邮箱:
示例代码(以.NET为例)
// 假设这是登录接口的处理逻辑 public async Task<IActionResult> Login(string email, string password) { try { var signInResult = await _signInManager.PasswordSignInAsync(email, password, false, lockoutOnFailure: false); if (!signInResult.Succeeded) { // 提取认证失败的错误消息,可根据实际场景动态获取 string errorMsg = "A user with the specified credentials could not be found."; // 组装要上报的数据 var logPayload = new { UserEmail = email, ErrorReason = errorMsg, OccurredAt = DateTime.UtcNow.ToString("o") }; // 调用你的REST API using (var httpClient = new HttpClient()) { var jsonContent = JsonSerializer.Serialize(logPayload); var requestContent = new StringContent(jsonContent, Encoding.UTF8, "application/json"); await httpClient.PostAsync("https://你的API地址/日志接口", requestContent); } return BadRequest("登录失败"); } return Ok("登录成功"); } catch (Exception ex) { // 捕获抛出的异常,匹配目标消息 if (ex.Message.Equals("A user with the specified credentials could not be found.", StringComparison.OrdinalIgnoreCase)) { var logPayload = new { UserEmail = email, ErrorReason = ex.Message, OccurredAt = DateTime.UtcNow.ToString("o") }; using (var httpClient = new HttpClient()) { var jsonContent = JsonSerializer.Serialize(logPayload); var requestContent = new StringContent(jsonContent, Encoding.UTF8, "application/json"); await httpClient.PostAsync("https://你的API地址/日志接口", requestContent); } } return StatusCode(500, "服务器错误"); } }
二、从已上报的Application Insights日志中捕获
如果要从已存入AI的日志里提取数据,可通过以下方式实现:
1. 使用连续导出+Azure函数
- 配置Application Insights的连续导出,将异常日志导出到Azure存储账户(Blob/Table)
- 创建Azure函数,监听存储账户的新增文件/数据,解析JSON结构中的
Exception.Message字段 - 提取匹配目标消息的条目,同时获取日志中附带的用户邮箱(需确保上报日志时已将邮箱存入
customDimensions),然后调用你的REST API
2. 使用Kusto查询+逻辑应用
- 在Application Insights的Analytics中编写筛选查询:
exceptions | where message == "A user with the specified credentials could not be found." | project OccurredTime = timestamp, UserEmail = customDimensions["UserEmail"], // 需确保上报时已存入该字段 ErrorReason = message
- 创建Azure逻辑应用,定时运行上述查询,获取结果后调用你的REST API,将邮箱和错误信息传入
注意事项
- 若从AI日志提取邮箱,需在应用上报日志时,主动将用户输入的邮箱添加到
customDimensions中,否则无法从日志中获取 - 调用REST API时需添加重试机制,避免因网络问题导致日志丢失
- 注意数据加密,传输敏感信息(如邮箱)时使用HTTPS
内容的提问来源于stack exchange,提问作者Vihaan
相关产品推荐
相关产品推荐

