Get Sql Server Error Number from Exception

In order to get the error number from a system.data.sqlclient.sqlexception, you’ll need to iterate through all the inner exceptions of the current $_ exception in your catch{} block:

cls
try
{
	Get-SqlData -sqlserver "YourServerName" -dbname master -qry "SELECT 0/0"
}
catch
{
	for($ex = $_.Exception; $ex -ne $null; $ex = $ex.InnerException)
	{
		$ex | fl -Force
	}
}

This will iterate through all the inner exceptions until there are no more.  I’ll leave it to you when to stop iterating through the inner exceptions.  In this case, the exception we are looking for is nested 4 innerexceptions in:

Errors         : {System.Data.SqlClient.SqlError: Divide by zero error encountered.}
Class          : 16
LineNumber     : 1
Number         : 8134
Procedure      : 
Server         : YourServerName
State          : 1
Source         : .Net SqlClient Data Provider
ErrorCode      : -2146232060
Message        : Divide by zero error encountered.
Data           : {HelpLink.ProdName, HelpLink.ProdVer, HelpLink.EvtSrc, HelpLink.EvtID...}
InnerException : 
TargetSite     : System.Object ExecuteTSql(ExecuteTSqlAction, System.Object, System.Data.DataSet, Boolean)
StackTrace     :    at Microsoft.SqlServer.Management.Common.ConnectionManager.ExecuteTSql(ExecuteTSqlAction action, Object execObject, DataSet fillDataSet, Boolean catchException)
                    at Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteWithResults(String sqlCommand)

Edit: 20130103: You could also use $_.Exception.GetBaseException() to retrieve the first exception as well.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.