Библиотека TMCLibError — объект ошибки

Назначение и место в пакете

Библиотека TMCLibError (каталог src/libs/tmcliberror) содержит один класс — CTmcLibError. Это «конверт» для ошибки: флаг «ошибка была» и её текст. Код ядер и библиотек пакета передаёт такой объект вместо числовых кодов возврата: функция при сбое записывает в него текст, а вызывающий проверяет флаг и показывает текст пользователю.

Кто пользуется классом в Qt6-версии:

Кто Как
Ядра PlanarRT_H / PlanarRT_X (src/kernels/*) методы построения блоков и расчёта возвращают CTmcLibError или заполняют переданный по ссылке
Библиотека TMCIndan ошибки разбора задания и вывода
FieldView (src/fieldview) ошибки чтения файлов поля и топологии
Окно ядра (planrt_hview.cpp) текст ошибки шага Step:<номер>;<текст> показывается в строке состояния и в окне сообщения
Консольная проверка ядра apps/planarrt_common/runcheck.cpp печатает текст; признак ошибки — текст, отличный от "Error:no"

Класс опирается на CString и BOOL. В Qt6-версии их даёт слой совместимости compat/ (MFC поверх Qt), см. слой MFC поверх Qt.

Состав

Файл Роль
include/tmcliberror.h объявление CTmcLibError, константы CTMCRTHERROR_*, две функции имён файлов
libs/tmcliberror/tmcliberror.cpp реализация
libs/tmcliberror/stdafx.h системные заголовки <afx.h>, <afxwin.h>
libs/tmcliberror/stdafx.cpp файл предкомпилированного заголовка MSVC; в сборку Qt6 не входит

Класс CTmcLibError

Член Смысл
bIsError TRUE — ошибка зафиксирована
csError текст последней ошибки; без ошибки — "Error:no" (CTMCRTHERROR_0000)
CTmcLibError() создаёт объект «ошибки нет»
PutErrorMessage(char*), PutErrorMessage(CString) ставит флаг и заменяет текст
IsError() возвращает флаг
GetErrorMessage() возвращает текст
Clear() возвращает объект в состояние «ошибки нет»
operator= копирует флаг и текст из другого объекта

Константы CTMCRTHERROR_0001 … CTMCRTHERROR_0010 (все равны "Error:") и CTMCRTHERROR_STRLENMAX в коде пакета не используются. Функции MakeTempFileNameForBzCalcMn/MakeTempFileNameForBzCalcPl дописывают к имени файла суффиксы _for_Bz_Mn/_for_Bz_Pl и в Qt6-версии не вызываются.

Как пользоваться

Типичный шаблон — фрагменты kernels/planarrt_h/tmcrthnodediel.cpp:

    if( cError.IsError() ) return cError;            // предыдущий шаг уже с ошибкой — ничего не делать
    ...
    cError = SetRectMetal( pcNextBlockList, cParam ); // результат вложенного шага
    ...
    if( i1nte_atof_1( szBuf, &r1 ) != 0 )            // формула из задания не вычислилась
    {
        csBuf.Format("In{%s}%s; r=%lg;f=%lg; x=%lg; y=%lg",
            szBuf, expr_get_error(), r, f, x, y );
        cError.PutErrorMessage(csBuf);               // текст для пользователя
        return (_real)(0.0);
    };

Правила, которые следуют из кода:

  1. Сначала проверить, потом работать. Функции, принимающие объект по ссылке, начинают с if( cError.IsError() ) return; — цепочка операций останавливается на первой ошибке.
  2. Хранится только последняя ошибка. Повторный PutErrorMessage заменяет текст; если нужно сохранить причину, проверяйте IsError() сразу после каждого шага.
  3. Сброс — явно. Объект-поле класса сохраняет ошибку до вызова Clear(); классы ядер вызывают Clear() в конструкторе и в DeleteData().
  4. Потоки. Объект не защищён от одновременного доступа: у каждого потока должен быть свой объект, а результат передаётся основному потоку после завершения.

Подводные камни

  1. operator= принимает неконстантную ссылку, а в коде ядер объекту присваивается временный объект (cError = SetRectMetal(…)). По стандарту C++ так нельзя; сборка проходит, потому что библиотеки собираются с -fpermissive.
  2. Текст "Error:no" в состоянии без ошибки — обычная строка, а не пустая: признаком ошибки служит IsError(), а не непустой GetErrorMessage(). Код, который видит только текст (например, runcheck.cpp), сравнивает его со строкой "Error:no".

TMCLibError library — the error object

Purpose and place in the package

The TMCLibError library (directory src/libs/tmcliberror) contains a single class, CTmcLibError. It is an "envelope" for an error: an "error occurred" flag and its text. The kernel and library code of the package passes such an object instead of numeric return codes: on failure a function writes the text into it, and the caller checks the flag and shows the text to the user.

Who uses the class in the Qt6 version:

Who How
PlanarRT_H / PlanarRT_X kernels (src/kernels/*) block-building and computation methods return a CTmcLibError or fill one passed by reference
TMCIndan library task-file parsing and output errors
FieldView (src/fieldview) errors reading field and topology files
Kernel window (planrt_hview.cpp) the step error text Step:<number>;<text> is shown in the status bar and in a message box
Kernel console check apps/planarrt_common/runcheck.cpp prints the text; the error indicator is any text other than "Error:no"

The class relies on CString and BOOL. In the Qt6 version these are provided by the compatibility layer compat/ (MFC on top of Qt), see the MFC-on-Qt layer.

Contents

File Role
include/tmcliberror.h declaration of CTmcLibError, the CTMCRTHERROR_* constants, two file-name functions
libs/tmcliberror/tmcliberror.cpp implementation
libs/tmcliberror/stdafx.h system headers <afx.h>, <afxwin.h>
libs/tmcliberror/stdafx.cpp MSVC precompiled-header file; not part of the Qt6 build

The CTmcLibError class

Member Meaning
bIsError TRUE — an error has been recorded
csError text of the last error; with no error — "Error:no" (CTMCRTHERROR_0000)
CTmcLibError() creates a "no error" object
PutErrorMessage(char*), PutErrorMessage(CString) sets the flag and replaces the text
IsError() returns the flag
GetErrorMessage() returns the text
Clear() returns the object to the "no error" state
operator= copies the flag and the text from another object

The constants CTMCRTHERROR_0001 … CTMCRTHERROR_0010 (all equal to "Error:") and CTMCRTHERROR_STRLENMAX are not used in the package code. The functions MakeTempFileNameForBzCalcMn/MakeTempFileNameForBzCalcPl append the suffixes _for_Bz_Mn/_for_Bz_Pl to a file name and are not called in the Qt6 version.

How to use it

The typical pattern — fragments of kernels/planarrt_h/tmcrthnodediel.cpp:

    if( cError.IsError() ) return cError;            // previous step already failed — do nothing
    ...
    cError = SetRectMetal( pcNextBlockList, cParam ); // result of the nested step
    ...
    if( i1nte_atof_1( szBuf, &r1 ) != 0 )            // the formula from the task file failed to evaluate
    {
        csBuf.Format("In{%s}%s; r=%lg;f=%lg; x=%lg; y=%lg",
            szBuf, expr_get_error(), r, f, x, y );
        cError.PutErrorMessage(csBuf);               // text for the user
        return (_real)(0.0);
    };

Rules that follow from the code:

  1. Check first, then work. Functions that take the object by reference start with if( cError.IsError() ) return; — a chain of operations stops at the first error.
  2. Only the last error is kept. A repeated PutErrorMessage replaces the text; if you need to keep the cause, check IsError() immediately after each step.
  3. Reset explicitly. An object that is a class member keeps the error until Clear() is called; the kernel classes call Clear() in the constructor and in DeleteData().
  4. Threads. The object is not protected against concurrent access: each thread must have its own object, and the result is passed to the main thread after it finishes.

Pitfalls

  1. operator= takes a non-const reference, while in the kernel code a temporary object is assigned to the object (cError = SetRectMetal(…)). Standard C++ does not allow this; the build succeeds because the libraries are compiled with -fpermissive.
  2. The text "Error:no" in the no-error state is an ordinary string, not an empty one: the error indicator is IsError(), not a non-empty GetErrorMessage(). Code that sees only the text (for example, runcheck.cpp) compares it with the string "Error:no".