Contents
- 1 Обработка ошибок в Qlikview
- 1.1 ErrorMode
- 1.2 ScriptError
- 1.3 ScriptErrorDetails
- 1.4 ScriptErrorCount
- 1.5 ScriptErrorList
Существует пять специальных переменных, которые можно использовать для обработки ошибок в сценарии:
- ErrorMode
- ScriptError
- ScriptErrorDetails
- ScriptErrorCount
- ScriptErrorList
ErrorMode
Определяет действие, которое будет выполнено QlikView при возникновении ошибки во время выполнения сценария. По умолчанию переменная равна 1 (ErrorMode=1), скрипт остановится и пользователю будет предложено ввести действие («non-batch» режим). С помощью значения параметра ErrorMode=0 QlikView будет игнорировать ошибки и продолжит выполнение скрипта со следующего оператора сценария. Если установить ErrorMode=2, то QlikView выдаст сообщение «Выполнение скрипта не удалось…» при неудаче сразу же, без запроса действия от пользователя.
Пример:
ScriptError
Код ошибки последнего выполненного участка кода. Эта переменная сбрасывается в 0 после каждого успешно выполненного участка скрипта (сценария загрузки). Если произошла ошибка, то значению переменной будет присвоен код внутренней ошибки QlikView. Код ошибки представляет собой двойное значение из числа и текстового значения.
Коды ошибок:
- 1 No Error — 1 Нет ошибки;
- 2 General Error — 2 Общая ошибка;
- 3 Syntax Error — 3 Ошибка синтаксиса;
- 4 General ODBC Error — 4 Общая ошибка ODBC;
- 5 General OLEDB Error — 5 Общая ошибка OLE DB;
- 6 General XML Error — 6 Общая ошибка XML;
- 7 General HTML Error — 7 Общая ошибка HTML;
- 8 File Not Found — 8 Файл не найден;
- 9 Database Not Found — 9 База данных не найдена;
- 10 Table Not Found — 10 Таблица не найдена;
- 11 Field Not Found — 11 Поле не найдено;
- 12 File Has Wrong Format — 12 Неверный формат файла;
Пример:
set ErrorMode=0; load * from abc.csv; if ScriptError=8 then exit script; //no file; end if |
Есть еще один способ, который можно использовать:
set ErrorMode=0; load * from abc.csv; if ‘$(ScriptError)’=‘File Not Found’ then exit script; end if |
ScriptErrorDetails
Возвращает подробное описание ошибки для некоторых кодов, которые были указаны выше. Самое главное это то, что переменная будет содержать сообщение об ошибке, которое возвращает драйвер ODBC и OLEDB для кодов ошибок 3 и 4.
ScriptErrorCount
Возвращает общее количество участков кода (statements), которые привели к ошибках во время выполнения сценария загрузки. Эта переменная всегда сбрасывается в 0 в начале выполнения скрипта.
Пример:
Set ErrorMode=0; Load * from abc.csv; if ScriptErrorCount >= 1 then exit script; end if |
ScriptErrorList
Эта переменная будет содержать объединенный перечень всех ошибок скрипта, которые произошли в ходе последней загрузки. Каждая ошибка — это отдельная строка. Значения всех вышеприведенных переменных сохраняется после выполнения скрипта. Значения ScriptError, ScriptErrorDetailed, ScriptErrorCount и ScriptErrorList для обработки ошибок в скрипте зависят от использования ErrorMode = 0.
Error Handling – Any system needs application or logic to handle error, the same logic is applicable to Qlikview…
This document is general overview and guideline around Qlikview Error Handling, suggesting best practices and providing some sample existing functions to achieve it, In brief document covers following functional areas:
- Overview to Qlikview Error Handling
- Customizing default Qlikview behaviour on encountering error
- Defining exceptions – information, warning or errors
- Defining Custom behaviour and application specific error messages
Qlikview Error Handling
Qlikview scripting allow error handling primary using Qlikview ErrorMode functions, where Value of ErrorMode defines, what type of behaviour application will have. Primary following are main ErrorMode values are used
Error Mode | Qlikview Behaviour |
0(Zero) |
No Error Continue to next operation |
1 |
On encountering error, waits for user response (Default) |
2 |
Stops execution of the job – Failure |
Code in development should have always ErrorMode=1, Production Environment (batch modes) generally have value as 2, or in specific scenarios it can have 0 also…
Note:
Setting variable ErrorMode = 0 ignores any error and continue to next code syntax, but return code from that script will be non-zero(failure), so generally in batch event, where return code of a Qlikview is required to trigger the next job, it will create an issue.
Defining Exceptions – Information, Warning or Errors
Now based on the business functionality, any processing issue can be termed as Information/Warning or Error; these are further classified down as:
- System Generated Errors
-
Custom
- Warning – Generally overriding System Error
- Errors – Errors Generated at specific event
- Warning – Generally overriding System Error
Custom Messages
Warning:
Generally these are the errors, which are not business critical, but needs to be reported/logged
Example
Generally critical production system has BCP features(hot/cold), which means once primary system is down, secondary becomes operation and accessible. Certain organization had Production system copy/backup, but no automated BCPing(or failover) process, So Once Primary system is down, application accessing the primary application has to now access new application, generally different location/credential
Flow Logic
So in the above case, Qlikview ignores error messages, when system1 does not respond and continues to next system2, thus overriding default Qlikview behaviour of failure
Custom Error:
In the same process flow, there is section “Data validation fails” – This section can be used to check a number of business logics – like number of rows, %change in volume more than a threshold and based on that process can decide to action according
Assuming, if both systems are responding fine, but number of rows returned is zero, so in this case it is not a system error, but a processing error and hence require a custom errors
Attached external library:
Sample error library, which can be used to achieve and experiment certain standard process behaviour. These files can be customized for specific application/group to cater delivery of customized messages/warning or errors
Other useful areas from application
- Set Statement used to execute a complete function – ERRORLOG
Сегодня, в этой статье, мы поговорим о системных переменных по работе с ошибками «Error Variables» и о том, как и где их можно использовать в своем приложении.
В Qlik Sense и QlikView «ErrorVariables» доступны для:
- Определения, какие действия следует предпринять, если во время выполнения сценария возникает ошибка
- Предоставления информации об ошибках, возникающих во время выполнения сценария
В этой статье мы рассмотрим следующие четыре переменные «ErrorVariables»:
- ErrorMode
- ScriptError
- ScriptErrorCount
- ScriptErrorList
Из этих 4 переменных, только одна переменная ErrorMode является переменной, задаваемой пользователем. Эта переменная определяет, что должно произойти, если во время выполнения скрипта возникает ошибка. Эта переменная устанавливается в скрипте следующим образом:
Переменная ErrorMode может принимать одно из трех значений: 0, 1 или 2. По умолчанию, переменная ErrorMode устанавливается в значение 1. Это означает, что при возникновении ошибки при выполнении скрипта скрипт остановится и предложит пользователю выполнить действие. Если для переменной ErrorMode установлено значение 0, то ошибка будет проигнорирована, и выполнение скрипта будет продолжено. Если для параметра ErrorMode установлено значение 2, сценарий завершится с ошибкой и остановится. Переменная ErrorMode должна быть установлена в начале сценария или перед секцией скрипта, где вы знаете, что могут возникнуть ошибки, которые вы хотели бы обработать особенным способом. Как только параметр ErrorMode будет установлен, он останется прежним, если переменная ErrorMode не будет перезагружена / изменена позже в скрипте. Например, вы можете установить для переменной ErrorMode значение 0, если в вашем скрипте есть область, которая может вызывать ошибки, которые вы хотели бы игнорировать (не останавливать выполнение сценария). В этом случае вам может потребоваться установить ErrorMode обратно в 1, если вы хотите, чтобы в дальнейшем сообщалось о других ошибках в скрипте.
Посмотрим, как будут отображаться сообщения об ошибках, если мы запустим простой сценарий ниже, чтобы загрузить группу файлов Excel, которые начинаются с «Book». Обратите внимание, что все загружаемые файлы не включают поле «MonthlySales».
Если перед этим скриптом, переменную ErrorMode выставили в значение «0» (SetErrorMode= 0), то когда скрипт завершит свою работы мы увидим следующее:
Обратите внимание, что скрипт завершил выполнение, хотя произошла ошибка. Теперь посмотрим, что произойдет, если мы оставим значение по умолчанию (ErrorMode= 1) или установим ErrorMode= 2.
Здесь выполнение скрипта остановилось при возникновении ошибки, предоставив возможность нажать кнопку «Close», исправить сценарий и перезагрузить данные снова.
В отличие от переменной ErrorMode переменные ScriptError, ScriptErrorCount и ScriptErrorList инициализируются не пользователем, а самой системой Qlik Sense или QlikView, которые предоставляют информацию об ошибке, которая была обнаружена при выполнении скрипта. Переменная ScriptError вернет код ошибки. Список кодов ошибок и их описания можно найти в справке Qlik Sense (или QlikView). ScriptErrorCount возвращает количество операторов, вызвавших ошибку во время выполнения скрипта. Наконец, переменная ScriptErrorList возвращает список ошибок, возникающих при выполнении сценария. Если имеется более одной ошибки, они разделяются переносом строки. Эти ошибки могут быть доступны в скрипте или через пользовательский интерфейс. В скрипте вы можете просто ссылаться на переменную ScriptError, чтобы найти его значение. Например, в приведенном ниже скрипте я могу проверить код ошибки 8 («Файл не найден»), чтобы определить, отсутствует ли загружаемый файл.
Переменные «ErrorVariables» также могут быть доступны в пользовательском интерфейсе через объект «Текст и изображение» (Text & image). В измерении объекта «Text& image» просто введите знак равенства и имя переменной:
Чтобы вернуть что-то вроде этого:
Переменные «ErrorVariables» полезны и просты в использовании. Например, мы, в своих проектах, чаще всего используем ErrorMode= 0 там где мы предполагаем, что существует вероятность того, что скрипт может вернуть ошибку, которую можно игнорировать. Это также полезно, если вам нужно контролировать путь выполнения скрипта на основе ошибки. Вы можете узнать больше об ошибках в справке Qlik Sense (или QlikView).
Recently, one of our customers came up with this requirement: Create a QVD with an incremental load. But, then there came a problem-”How would I do an increment load on a QVD, when it doesn’t exist in the first place? “ (Wait, it will be confusing, if you don’t know about incremental load, check it here, http://www.learnallbi.com/incremental-load-in-qlikview-part1/ ) then I thought, if at all I could trap those errors and use them for my convenience, I’d be able to do this and there began my search for error handling in Qlikview.
To my luck, Qlikview did mention about it in their manual, not very detailed though. So I thought I would give head start to those who would be trying to do their own error handling in Qlikview like me.
My program is simple, I need to do an incremental load on a QVD (Let’s call it Stage 2 QVD), which stores snapshots of an existing data (Stage 1 QVD). So, I don’t need to use any unique identifiers for this type of incremental load, just concatenate new data with a new date-stamp and store it away.
So, first I will check whether Stage 2 QVD exists? If not, create it with first set of data. Oh, it’s already there? Then go take data from it and add new set of data from Stage 1 QVD, to it. There you go, quite simple!
So, now how would I handle that error, if that Stage 2 QVD is not there? Don’t freak out! Qlikview has it covered for us. First set ErrorMode to 0 in the script,
Set ErrorMode=0;
This is manual override for errors in Qlikview. Careful, now though, you wouldn’t be able to see any errors in your application from this moment on. Next as our requirement is to find whether Stage 2 QVD exists or not? for this we will write a simple IF ELSE statement.
So, IF ScriptError=8 or ScriptError=10, here ScriptError=8 is “File not Found” and ScriptError=10 is “Table Not Found”, So if either of these errors has occurred then create a Stage 2 QVD.
ELSEIF ScriptError=0 ( I have used 0 as No Error, as when no errors are there ScriptError will stay 0. It will only become 1 after finishing first statement execution or finishing the script ) which means if QVD exists then take data from Stage 2 QVD and append new data from Stage 1 QVD and store the same into that Stage 2 QVD which would replace existing QVD.
If any other error than mentioned occurs in the script, it will exit from the load.
Refer to Qlikview 11 reference manual for more detailed execution of these. I will quote error handling section mentioned in reference manual for your convenience here.
ErrorMode:
This variable determines what action is to be taken by QlikView when an error is encountered during script execution. By default (ErrorMode=1) the script execution will halt and the user will be prompted for action (non-batch mode). By setting ErrorMode =0 QlikView will simply ignore the failure and continue script execution at the next script statement. By setting ErrorMode =2 QlikView will trigger an “Execution of script failed…” error message immediately on failure, without prompting the user for action beforehand.
Example:
set ErrorMode=0;
ScriptError:
Returns the error code of the last executed script statement. This variable will be reset to 0 after each successfully executed script statement. If an error occurs it will be set to an internal QlikView error code. Error codes are dual values with a numeric and a text component. The following error codes exist:
1 No error
2 General Error
3 Syntax Error
4 General ODBC Error
5 General OLE DB Error
6 General XML Error
7 General HTML Error
8 File Not Found
9 Database Not Found
10 Table Not Found
11 Field Not Found
12 File Has Wrong Format
Example:
set ErrorMode=0;
load * from abc.qvw;
if ScriptError=8 then
exit script;
//no file;
end if
ScriptErrorDetails:
Returns a more detailed error description for some of the error codes above. Most importantly this variable will contain the error message returned by ODBC and OLE DB drivers for error codes 3 and 4.
ScriptErrorCount:
Returns the total number of statements that have caused errors during the current script execution. This variable is always reset to 0 at the start of script execution.
ScriptErrorList:
This variable will contain a concatenated list of all script errors that have occurred during the last script execution. Each error is separated by a line feed.
References : Qlikview Reference Manual v11
Surprise, loading data into Qlik is not always easy. But we already know you weren’t fooled when the salesperson confidently declared, “Any trained monkey can load your data into Qlik”. As data models get more complex I find myself joining, keeping, concatenating, mapping, resident loading and dropping tables. The Qlik script logic and syntax involved is not necessarily what I would label easy. Whether we use QlikView or Qlik Sense, these are some common scripting errors and how to resolve them. Also, please remember that the Qlik Community has always been an excellent place to get help for QlikView script errors you come across.
1. Comma Management
Symptom: All I did was comment some fields.
Likely Cause: Forgot to delete comma from what is now the last field.
This is an error we all make. The key here is to learn to recognize it quickly from the generated error messages that don’t really explain the cause. Just like in English grammar, we need commas between field names in a list and obviously we will remove the comma after the last field. Learn the general syntax rules regarding use of colons, semicolons, quotes and commas.
Forgot to remove comma from line 5 not to mention we still need the semicolon that is now commented.
The corrected code.
2. Missing QVD Directory
Symptom: I get a non-descript error or “Failed to open file in write mode…”
Likely Cause: Reference to a file location that does not exist.
This QlikView script error usually occurs when we are storing a QVD to a folder location that does not yet exist. It seems to me that in older versions of QlikView, the resulting error message was pretty much blank. The new error is much better. Make a mental note to always create the QVD folder in the file system before running this command in the QlikView script.
We simply added the folder to the directory so that Qlik would find the location when the script is executed.
3. Forgetting to Drop Extra Tables
Symptom: Why do I have synthetic keys all of a sudden?
Likely Cause: Not Dropping Tables on a resident load.
There are many times when, for whatever reason, we must load a table again from a resident load. When the field mix in the new table is slightly different because we added a field or we renamed a field, this has the potential to create a large synthetic key. So if we resident load a table and all of a sudden we have a synthetic key, we likely forgot to drop the first version of the table.
This is the original script. A common task, but aren’t we missing something?
Note that we now have an undesired synthetic key.
The corrected script includes a drop statement to trash the original table.
4. Neglecting to account for table concatenation
Symptom: I lost the new version of the table.
Likely Cause: Automatic Concatenation on resident load.
This is related to the prior situation. If we do a resident load to create a new version of the table and the table viewer completely loses the new and old versions of the table, it could send us into a panic. “What happened to my table?” What we might not remember is that when Qlik loads a new table that shares the exact same fields as a prior loaded table, the new table will be concatenated to the old table. And then because we subsequently drop the first table, there is no table left with our data. Adding a noconcatenate quickly solves the problem by telling Qlik to keep the tables separate.
Because the field mix of the 2 tables is identical, the tables will be automatically concatenated, which is not what we want here.
The simple addition of noconcatenate ensures the tables will remain separate at which point our drop statement will only apply to the original data table.
5. Cross joined tables
Symptom: My Qlik reload locked up.
Likely Cause: Joins with no keys.
When I first encountered a “stuck” script execution window, my heart sunk. “Gee, QlikView sure is buggy.” Of course, this was not a case of Qlik being buggy. Qlik was actually working very hard to create associations between a few tables. The problem was that I had joined one table to another with a typo between what I intended to be the key fields. When using the join keyword be mindful of the fields that Qlik will identify as keys and double-check to be sure they are named exactly the same. If the fields do not match, Qlik will associate every row of one table to every row of the other. This joining process can slow down the script at best and take your server down at worst. If our script appears to stop running for more than a few minutes this is the likely cause. Either way, this was not the resulting table we were looking for. Table 1: 100,000 rows Table 2: 5,000 rows Joined table: 500,000,000 (That’s 5 hundred million. Ugh.)
Qlik is hard-at-work joining every row to every row.
Notice that the fields I intended the join to occur over are not EXACTLY the same.
In this case my resulting table has 40 million records (20,000 x 20,000)
After I rename the field to be exactly like the field in the first table, I am back down to 20,000 records. Perfect.
6. Repeating Facts after Join
Symptom: My joined table has more records than it started with.
Likely Cause: Left joining with repeating keys
I find this to be a data error that is very common and overlooked by many developers. Picture a transaction table where we simply want to left join the Customer Name into. This seemingly harmless action unfortunately might inflate the actual transaction expressions in our dashboard. This is because if a Customer ID from the right table has any repeats, the resulting table will add those repeats to the transaction table. If the right table has no repeated keys, then we are fine. But when doing such an action, use the lastvalue function with a group by or similar function to ensure you are only taking one ID. Whatever you do, please do not rely on a distinct qualifier with the left join as we will accidentally remove some records from the left transaction table as well because the resulting table will also take on the distinctiveness. Checking for row counts in the table viewer before and after our joins is a good way to check the row counts.
This is a common left join. But there is trouble afoot.
We should only have 19 transactions. But because a Customer ID is repeated in the Customer table, I now have 26 lines.
Here are the corrections. We are ensuring that only 1 record will be joined to the transactions for each unique ID.
Now we are back to 19 records.
Here is the good data and bad data side-by-side. Obviously, we do not want to inflate our primary metric.
Qlik Freak came up with another list of gripes that are also extremely funny so check that out. Surely, we are just scratching the surface of the QlikView script errors that can occur. But if we understand these basic pitfalls, we are in a state to better deal with any script or data error that we might run across. What Qlik script errors have plagued your coding?
Сообщения об ошибках QlikView, отображаемые во время выполнения скрипта, во время перезагрузки или сразу после запуска скрипта, являются ключом к пониманию того, какова природа ошибок в вашем коде. После обнаружения ошибки и появления диалогового окна с ошибкой, вы можете просмотреть ошибку и нажать OK или Cancel (Отмена) в диалоговом окне Script Error (Ошибка скрипта). Если у вас открыт отладчик, нажмите Close (Закрыть), затем нажмите Cancel (Отмена) в диалоговом окне Sheet Properties (Свойства листа). Снова войдите в редактор скрипта и проверьте свой скрипт, чтобы исправить ошибку. Ошибки могут возникать в результате ошибок в синтаксисе, формулах или выражениях, ошибок соединения, циклической логики или любых других проблем в вашем скрипте.
Ниже представлено несколько распространенных сообщений об ошибках, с которыми вы столкнетесь при разработке скрипта QlikView. Первая из них, показанная на следующем скриншоте – это синтаксическая ошибка, которую мы получили при запуске кода, в котором пропущена запятая после Sales. Это распространенная синтаксическая ошибка. Это выглядит немного загадочно, но ошибка содержится в отображаемом фрагменте кода. В диалоговом окне ошибки нет точных сведений о том, что в определенном месте должна быть запятая, но поработав с QlikView вы быстро начнете понимать кто к чему.
Следующая ошибка – ошибка циклической ссылки. QlikView автоматически обработает эту ошибку. Вы можете принять исправление QlikView, отвязав одну из таблиц в круговой ссылке (см. модель данных в средстве просмотра таблиц (Table Viewer) для получения дополнительной информации о том, какая таблица отвязана, или просмотрите диалоговое окно Document Properties (Свойства документа) на вкладке Tables (Таблицы), чтобы узнать, какая таблица отмечена как Loosely Coupled (Слабо связанная). В качестве альтернативы вы можете выбрать другую таблицу для отвязывания на вкладке Document Properties (Свойства документа) на вкладке Tables (Таблицы) или вернуться в скрипт и исправить циклическую ссылку одним из предложенных методов.
Другой распространенной проблемой является ошибка неизвестного оператора, которая может быть вызвана ошибкой при написании скрипта – пропущенными запятыми, двоеточиями, точками с запятой, скобками, кавычками или неправильно написанной формулой. В случае, показанном на следующем скриншоте, система обнаружила неизвестный оператор, а именно строку Customers, которую QlikView пытается интерпретировать как Customers Load *…. Чтобы исправить эту ошибку, добавьте двоеточие после Customers следующим образом: Customers:
Бывают случаи, когда загрузка скрипта завершается ошибкой. Попытка сохранить QVD или CSV в файл, заблокированный другим просматривающим его пользователем – вот пример одной из таких ошибок. Другой пример: у вас есть два поля с одинаковым именем в вашем операторе загрузки. Отладчик может помочь вам найти строки скрипта, в которых присутствует скрытая ошибка.