简体   繁体   中英

Catch exception and save to SQL Server

I'm catching an exception and I want to write this to SQL Server, but my program doesn't write...

I haven't received any error, but in SQL Server I haven't found anything...

catch (Exception f)
{ 
    String error = f.ToString();
    SqlConnection konekt = new SqlConnection(connectionstring);

    SqlCommand prikaz = new SqlCommand("insert into ERROR_LOG (ULOHA, OPERACE, POPIS, MESSAGE, DATUM) values ('3', '3', 'Chyba v ExportNOHEL', @error, @datum)", konekt);
    konekt.Open();
    prikaz.Parameters.AddWithValue("@error", error);
    prikaz.Parameters.AddWithValue("@datum", DateTime.Now);

    prikaz.ExecuteNonQuery();

    konekt.Close();
 }

Have you any idea where is the problem?

If you aren't getting any errors, and you are 100% sure that you are indeed writing to the correct database, then it may be that you have an ambient transaction, such as TransactionScope (which is rolling back your transaction)

A way to check this is to place a breakpoint on konekt.Close(); and then switch to SQL Query Analyzer and do

select * from error_log (NOLOCK) 

to see if the log is there. If it is, and then getting rolled back when you continue your code, you can suppress the ambient transaction as follows:

        using (new TransactionScope(TransactionScopeOption.Suppress))
        using (var konekt = new SqlConnection(connectionstring))
        using (var prikaz = new SqlCommand("insert into ERROR_LOG (ULOHA, OPERACE, POPIS, MESSAGE, DATUM) values ('3', '3', 'Chyba v ExportNOHEL', @error, @datum)", konekt))
        {
           konekt.Open();
           prikaz.Parameters.AddWithValue("@error", "ASASAS");
           prikaz.Parameters.AddWithValue("@datum", DateTime.Now);
           prikaz.ExecuteNonQuery();
           konekt.Close();
        }

Depending on the datatype which you have it maybe that the data is getting truncated if error is too large. This might help:

String or binary data would be truncated SQL Error

虽然你所做的事情看起来没有任何错误,但是将SQL语句硬编码到c#中会使调试变得困难,我建议在数据库中为此创建一个新的存储过程,然后你可以更好地监控动作,通过在存储过程中创建一个正确的try catch,您可以更好地发现出错的地方。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM