How to use exceptions in this scenario?

I have a method that processes a set of records. This method returns true \ false after processing. Therefore, if all the records are processed (making some db updates), it will return true.Now, suppose that after processing 1 record, there is some exception, should I write result = false (returns at the end of the method result) in catch catch? And allow processing of other records?

+3
source share
3 answers

Continuing to add data to the database when a single record fails is almost always wrong. Records are very often related. They are a collection of transactions in a bank account. Or a package of orders from a customer. Adding them with the absence of one of them is always a problem.

Not only are you giving your client a huge problem with a new batch containing a single corrected record, you too easily allow someone to simply ignore the error. A type of error that is not detected or causes problems until much later. Invariably with huge costs associated with fixing the error.

. , . , , SqlTransaction BeginTransaction() . Call Commit(), , Rollback() catch.

, , . . .

+1

, , - . , , result = false catch, , ", - ...". - , .

, . -, , ( ...)

, , - ...

, , , - ...

0

I think it could be something like this

    int count = 0;
    foreach( item in list)
    {

    try
    {
     //update DB
     ++count;
    }
    catch(Exception ex)
    {
         //log exception
    }
    if(count == list.Count)
      return true;
     else return false;

   }

Another way

 bool result = true;
 foreach( item in list)
 {

   try
   {
     //update DB
   }
   catch(Exception ex)
   {
      //log exception
      result = false;
   }
  return result;
 }
-1
source

Source: https://habr.com/ru/post/1740909/


All Articles