'Find where my code is failing to perform the desired task

I am processing some records as shown below using cursor and stored procedure. Out of 100 records, 40 are being processed successfully but the rest 60 are not. Then the next block of code is being processed. There also, same success rate applies.

Is there any way how to see where the code is breaking? OR How can I apply try catch block? i.e. if error occurs then log it and then resume where it left, Fetch the next record and process it.

Can someone please guide me how to set up some process to find the errors while looping. Thank you

    -- one block of code----
    DECLARE @expiry_date datetime,
    @ttokenid varchar(10),
    @id_traveltoken numeric(10,0),
    @id_smartcard numeric(10,0)

    SET @expiry_date = GETDATE()

    SET @csr = CURSOR FOR
        SELECT t1.id_traveltoken, sc.id_card
        FROM token t1
        INNER JOIN smartCard sc ON t1.SmartCardID = sc.id_smartcard
        
    OPEN @csr 
    FETCH NEXT FROM @csr INTO @id_traveltoken, @id_smartcard

    WHILE @@FETCH_STATUS = 0
    BEGIN
         SET @ttokenid = convert(varchar(10), @id_traveltoken)               
        
         EXEC  usp_checkPermit @ttokenid, @id_smartcard, @expiry_date
        
      FETCH NEXT FROM @csr INTO @id_traveltoken, @id_smartcard
    END; 

    CLOSE @csr ;
    --another similar block of code----


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source