在.NET6控制台应用中使用RestSharp获取PATCH请求错误响应详情
解决方案
问题出在你设置了client.Options.ThrowOnAnyError = true;,这个配置会让RestSharp在收到非2xx状态码(比如400 BadRequest)时直接抛出异常,不会将响应体中的错误详情填充到RestResponse对象里。要获取Postman中看到的错误内容,需要调整配置并修改代码逻辑:
关闭自动抛出异常的配置
将client.Options.ThrowOnAnyError = true;改为client.Options.ThrowOnAnyError = false;,这样即使请求返回400,RestSharp也会返回完整的RestResponse对象,而非直接抛出异常。手动处理响应状态码
执行PATCH请求后,通过responsep.StatusCode判断状态,如果是400,直接读取responsep.Content获取错误详情。修改后的代码示例
static RestResponse createOrUpdateElement(RestClient client, RestRequest request, string urlSuffix) { RestResponse response = new RestResponse(); RestResponse responsep = new RestResponse(); // 关闭自动抛出异常,保留响应内容 client.Options.ThrowOnAnyError = false; try { response = client.Get(request); if (response.IsSuccessStatusCode) { var existing = JsonSerializer.Deserialize<JsonElement>(response.Content); if (existing.TryGetProperty("value", out JsonElement value)) { if (value.GetArrayLength() == 0) { client = GetRestClient(urlSuffix); response = client.Post(request); } else { JsonSerializer.Deserialize<JsonElement>(value[0]).TryGetProperty("SystemId", out JsonElement systemId); request.AddHeader("If-Match", "*"); client = GetRestClient(urlSuffix + "(" + systemId.ToString() + ")"); // 执行PATCH请求,此时即使返回400也不会抛出异常 responsep = client.Patch(request); // 检查是否是400错误,读取错误详情 if (responsep.StatusCode == System.Net.HttpStatusCode.BadRequest) { string errorDetails = responsep.Content; // 这里可以处理错误详情,比如打印、记录日志等 Console.WriteLine("400错误详情:" + errorDetails); } } } } } catch (Exception ex) { // 仅处理网络错误、序列化错误等真正的异常,而非状态码导致的异常 responsep.ResponseStatus = ResponseStatus.Error; responsep.ErrorMessage = ex.Message; responsep.ErrorException = ex; } // 注意:原代码返回的是response,若需返回PATCH请求的响应,可改为return responsep; return response; }额外说明
- 如果需要对特定状态码抛出异常,可在获取响应后手动判断(比如对5xx状态码抛出异常),保留4xx状态码的响应内容。
- 确保
request的配置(请求头、请求体等)和Postman完全一致,避免因请求参数差异导致的错误内容不一致。
内容的提问来源于stack exchange,提问作者Jack Casas
相关产品推荐
相关产品推荐

