Tuesday, April 12, 2016

Extracting the real reason for a 500 error from Reporting Services

One of the things that makes our lives more difficult is when Microsoft returns generic error messages that simply mean "Something went wrong". In this case we find that Reporting Services returns error 500 when the report is missing, invalid, missing a data source, is called with bad parameters, or any of a hundred other possible problems.

Up until now I have simply pasted the URL into a web browser to see the real problem I really wanted something better.

The code is fairly simple. I create a web request and grab the response.

Dim URL As String = "http://MyReportServer/ReportServer?/REQUISITION&rs:Format=PDF&rs:Command=Render"
Dim Request As System.Net.HttpWebRequest = Nothing
Dim Response As System.Net.HttpWebResponse = Nothing
Dim Stream As System.IO.Stream = Nothing

Request = System.Net.WebRequest.Create(URL)
Request.UseDefaultCredentials = True
Request.PreAuthenticate = True
Request.Timeout = 300000
Response = Request.GetResponse()
Stream = Response.GetResponseStream()

If a problem occurs the call to GetResponse will throw an exception indicating the server returned a 500 server error. But the response stream actually contains the real error message embedded in an HTML page. So in the catch block try this code...

Dim ErrorMsg As String = ex.Message
If TypeOf ex Is System.Net.WebException Then
   Dim WE As System.Net.WebException = DirectCast(ex, System.Net.WebException)
   Dim Buffer(WE.Response.GetResponseStream().Length) As Byte
   Dim HTML As String
   Dim pLI As Integer, pA As Integer
   WE.Response.GetResponseStream().Read(Buffer, 0, WE.Response.GetResponseStream().Length)
   HTML = System.Text.Encoding.Default.GetString(Buffer)
   pLI = HTML.IndexOf("<li>") + 4
   pA = HTML.IndexOf("<a ", pLI)
   If pLI > -1 AndAlso pA > -1 Then
      ErrorMsg = HTML.Substring(pLI, pA - pLI)
   End If
End If
Throw new Exception(ErrorMsg)

No comments:

Post a Comment