You can do this by creating a class that implements the ISQLExceptionConverter
interface.
Here is an example implementation for SQL Server:
Public Class MsSqlExceptionConverter
Implements ISQLExceptionConverter
Private Enum SqlServerError As Integer
ConstraintViolation = 2627
ConstraintConflict = 547
End Enum
Public Function Convert(ByVal adoExceptionContextInfo As Global.NHibernate.Exceptions.AdoExceptionContextInfo) As System.Exception _
Implements Global.NHibernate.Exceptions.ISQLExceptionConverter.Convert
Dim sqle As SqlException = TryCast(ADOExceptionHelper.ExtractDbException(adoExceptionContextInfo.SqlException), SqlException)
If sqle IsNot Nothing Then
Select Case sqle.Number
Case SqlServerError.ConstraintConflict
Return New ConstraintConflictException(InternalExceptionMessages.ConstraintConflictOccured, adoExceptionContextInfo.SqlException)
Case SqlServerError.ConstraintViolation
Return New ConstraintViolationException(InternalExceptionMessages.ConstraintViolationOccured, adoExceptionContextInfo.SqlException)
End Select
End If
Return SQLStateConverter.HandledNonSpecificException(adoExceptionContextInfo.SqlException, adoExceptionContextInfo.Message, adoExceptionContextInfo.Sql)
End Function
End Class
To make use of this, define it in your NHibernate config file as follows:
<property name="sql_exception_converter">YourProduct.Infrastructure.NHibernate.ExceptionConverters.MsSqlExceptionConverter, YourProduct.Infrastructure</property>
Overall, this feature is (more or less) undocumented, but you can find some information on Fabio Maulo's blog.