You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在VB.Net中捕获400 Bad Request状态的错误信息

解决VB.Net中捕获400 Bad Request响应错误信息的问题

你的代码目前只是捕获到了WebException,但没有读取400响应返回的具体错误内容。要获取Postman里能看到的错误信息,需要在捕获异常后读取响应流的内容,修改后的代码如下:

Dim resp As HttpWebResponse
Dim request As HttpWebRequest = HttpWebRequest.Create("MyUrl")
request.Method = "POST"
request.ContentType = "application/json"
request.Headers.Add("authorization", "Bearer " + TokenAPI)
Dim PostString As String = JSON
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(PostString)
request.ContentLength = byteArray.Length
Using dataStream1 As Stream = request.GetRequestStream()
    dataStream1.Write(byteArray, 0, byteArray.Length)
End Using ' 自动关闭流,替代手动Close

Try
    resp = DirectCast(request.GetResponse(), HttpWebResponse)
    If resp.StatusCode = 201 Then
        MsgBox("OK")
    End If
    Return "ok"
Catch ex As WebException
    Dim rep As HttpWebResponse = DirectCast(ex.Response, HttpWebResponse)
    If rep IsNot Nothing Then
        ' 读取响应流中的错误信息
        Using reader As New StreamReader(rep.GetResponseStream(), Encoding.UTF8)
            Dim errorMessage As String = reader.ReadToEnd()
            ' 这里可以根据需要处理错误信息,比如弹窗显示或者返回
            MsgBox($"错误信息:{errorMessage}")
            Return errorMessage
        End Using
    End If
    Return "未知错误"
End Try

关键修改点:

  • 用Using语句处理request.GetRequestStream()和StreamReader,自动释放资源,避免手动关闭可能带来的问题
  • 在Catch块中,先判断ex.Response不为空(部分WebException可能没有响应对象)
  • 通过StreamReader.ReadToEnd()读取响应流的完整内容,这就是接口返回的具体错误信息
  • 可以根据业务需求,将错误信息弹窗显示或者作为返回值返回

内容的提问来源于stack exchange,提问作者Bladimir Silva Toro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 13:57:05