Handling Sql Custom Exception - c#

How to identify the custom error message raised from the sql stored procedure with c# code?
Stored Procedure the error will be raised like this
RAISERROR (N'This is message %s %d.', -- Message text.
10, -- Severity,
1, -- State,
N'number', -- First argument.
5); -- Second argument.
From the above, how to identify that the error is custom error message. (ie) Something like this
try{
--actual code here
}
catch(SqlException ex)
{
--how to check here that the exception is custom one
}

When you raise the error you can provide a MessageId instead of a Message text. This number will be found in the Number propertie of the Exception:
SQL:
RAISERROR(50001, 12, 1)
C#:
if (sqlException.Number == 50001)
{
throw new CustomSQLException(//whatever);
}

Related

Can I pass an error message from a C# executable out into a VBScript

I have a C# command executable I created. In it, I have built some error handling. I would like to be able to pass these thrown errors out of the program into another script that the users will have control over (in VBS). I have seen I can set the Environment.Exit integer, but can I send my error message?
As #SLaks mentioned: write the error message to STDERR. If you run your executable via the Exec method you can get the exit code and error message like this:
Set ex = CreateObject("WScript.Shell").Exec("C:\path\to\your.exe")
While ex.Status = 0
WScript.Sleep 100
Wend
exitcode = ex.ExitCode
errormsg = ex.StdErr.ReadAll

Customize Sql Exception message in catch

I ´m doing a form where the user can Insert/Delete/Add entities. I´m using Winforms c# and entity framework 4.
Ok, the user can delete objects. Now, those objects can be referenced by other entities, so if the user wants to delete it, he will get an exception.
I catch that exception so as to show him a message that says that that object is begin used in other objects.
The exception I got is (UpdateException). But this exception can be raised if there is an update issue too. Is there any way to get the error code from Sql using this exception? Because I do have the error code that throws when this happens.
If I use SqlException I can check its number, but that's not the exception I´m receiving.
Do you mean you want to see the full exception or you want the user to the see the exception?
If you want to the see exception, you could write it to a text file:
try
{
// do something
}
catch(SQLException sqlex)
{
using (var file = new StreamWriter(#"C:\Users\Home\Desktop\sqlException.txt"))
{
file.WriteLine(sqlex.ToString());
}
}
catch(Exception e)
{
using (var file = new StreamWriter(#"C:\Users\Home\Desktop\generalException.txt"))
{
file.WriteLine(e.ToString());
}
}
This will write the exception to a text file on your desktop (change directories as appropriate).

Converting MS Oracle client to Oracle Data Provider - OracleException

I'm converting a product from System.Data.OracleClient to Oracle.DataAccess.Client, and came across a question Here's a snippet of some code:
try
{
//some db code
}
catch (System.Data.OracleClient.OracleException ex)
{
if (ex.Code == 00904)
{
// log specific error
}
}
The problem is, Oracle.DataAccess.Client.OracleException has no Code property. It has a Number property. Is this the same thing? The docs say this about the property -
This error number can be the topmost level of error generated by
Oracle and can be a provider-specific error number.
The Code property contained the ORA- error code.
Yes, they are the same thing. Oracle.DataAccess.Client.OracleException.Number is the same info as System.Data.OracleClient.OracleException.Code.

How can I get the actual SQL that caused an SqlException in C#? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Obtain the Query/CommandText that caused a SQLException
I am working on some error handling code (using elmah) and the default setup only sends the error message. I would like to know the actual SQL that throws an error (i.e. "SELECT * FROM thisTableDoesNotExist")
This is what I have so far:
if (e.Error.Exception is SqlException)
{
//if SQL exception try to give some extra information
SqlException sqlEx = e.Error.Exception as SqlException;
e.Mail.Body = e.Mail.Body + "<div>" +
"<h1>SQL EXCEPTION</h1>" +
"<b>Message</b>: " + sqlEx.Message +
"<br/><b>LineNumber:</b> " + sqlEx.LineNumber +
"<br/><b>Source:</b> " + sqlEx.Source +
"<br/><b>Procedure:</b> " + sqlEx.Procedure +
"</div>";
}
And I would like to be able to also show the actual SQL. The database is SQL Server 2008 and SqlException is of type System.Data.SqlClient.SqlException.
Not possible. You'll need to catch the exception where the SQL command was executed, and then include your command text in your own custom exception. See Obtain the Query/CommandText that caused a SQLException.
You could have error handling code in your SQL, and when it encounters an error, you can send back the SQL that it attempted to run with a print or returns statement or however you want to return it to your application.
The best way to examine the exception is to put a breakpoint in your code where the exception happens and examine the values of the exception object graph.
Try the Message member of the InnerException like this:
sqlEx.InnerException.Message
It may not provide the exact SQL that failed but may give you more specific information such as the operation and the table name. The StackTrace member may also have some information.
If you can't get enough information on C# side you can use "SQL profiler" (part of complete MS SQL) to see what commands where executed.
Information on SQL Profiler http://msdn.microsoft.com/en-us/library/ms181091.aspx . You should also be able to use underlying Tracing API if you don't have profiler - http://msdn.microsoft.com/en-us/library/ms191006.aspx

Catch REFERENCE constraint exception from SQL in C#

What will be proper way to catch exception which throw SQL server when I deleting data with Reference constraint from C# code.
I want to show my users message like:
"I can't delete the data because is used"
, rather than of showing message like this:
The DELETE statement conflicted with the REFERENCE constraint ... The conflict ccurred*in database "rampa", table "dbo.doc", column 'kartica_id'.
Use this:
try
{
//Execute delete statement
}
catch (SqlException sqlEx)
{
//Handle exception
}
finally
{
//Close connection
}
All sql errors are thrown as SqlException and there are no specific errors. To find out what was error exactly, there is property SqlException.Number which is the same as SQL Error Code. You can find the list of codes here.
You can access the ConstraintException and map its fields however you want to your own preferred error output.
using System.Data;
try
{
// code that violates constraint
}
catch (ConstraintException exc)
{
// build output message you wish using exc.Message and other fields,
// return cleanly or rethrow as your own exception
}

Categories