Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Пробрасывание информации об ошибке через ВызватьИсключение #1488

Merged
merged 1 commit into from
Jan 21, 2025

Conversation

sfaqer
Copy link
Contributor

@sfaqer sfaqer commented Jan 14, 2025

Теперь при выбросе исключения с передачей ИнформацииОбОшибке в качестве параметра, создаётся новая ИнформацииОбОшибке которая с описанием оригинальной информации об ошибке и которая содержит оригинальную информацию об ошибке в Причина

Summary by CodeRabbit

  • New Features

    • Added a new test procedure to validate error handling and exception propagation
  • Bug Fixes

    • Refined exception handling logic to improve error reporting and specificity

Copy link

coderabbitai bot commented Jan 14, 2025

Walkthrough

The pull request introduces changes to the exception handling mechanism in the MachineInstance class, specifically modifying the RaiseException method. The changes refine how exceptions are processed, particularly distinguishing between error templates and non-template exceptions. A corresponding test case is added to validate the error handling behavior, ensuring that error information is correctly propagated when exceptions are re-thrown.

Changes

File Change Summary
src/ScriptEngine/Machine/MachineInstance.cs Modified RaiseException method to enhance exception handling logic, introducing clearer distinction between error templates and non-template exceptions
tests/global-funcs.os Added new test procedure Тест_ДолженПроверитьИнформацияОбОшибкеПробрасываетсяПриВызовеИсключения to validate exception re-throwing and error information propagation

Sequence Diagram

sequenceDiagram
    participant MachineInstance
    participant ExceptionHandler
    participant ParametrizedRuntimeException

    alt Is Error Template
        MachineInstance->>ExceptionHandler: Check IsErrorTemplate
        ExceptionHandler-->>ParametrizedRuntimeException: Create with template info
    else Not Error Template
        MachineInstance->>ExceptionHandler: Process non-template exception
        ExceptionHandler-->>ParametrizedRuntimeException: Create with direct exception info
    end
Loading

Possibly related PRs

Poem

🐰 Exceptions dance, a coding ballet
Where errors leap and templates play
With careful steps and logic bright
Our code now handles errors just right!
A rabbit's tale of error's might 🚀


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 07dbe5b and 3f7c479.

📒 Files selected for processing (2)
  • src/ScriptEngine/Machine/MachineInstance.cs (1 hunks)
  • tests/global-funcs.os (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/ScriptEngine/Machine/MachineInstance.cs
🔇 Additional comments (2)
tests/global-funcs.os (2)

81-81: LGTM! Test registration follows conventions.

The new test is properly registered in the test list following the existing naming conventions.


937-970: LGTM! Well-structured test with comprehensive assertions.

The test case thoroughly verifies error propagation by:

  1. Capturing the original error information
  2. Re-throwing it
  3. Verifying that both the description and cause are preserved

The test follows good practices:

  • Clear setup/action/verification structure
  • Descriptive assertion messages
  • Proper error handling
  • Consistent with other error handling tests

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/ScriptEngine/Machine/MachineInstance.cs (1)

1253-1259: LGTM! The enhanced exception handling logic improves error information propagation.

The changes properly distinguish between error templates and regular exceptions, ensuring that error information is correctly preserved and propagated. Consider extracting the exception creation logic into separate methods for better readability.

Consider this refactoring to improve readability:

-                if (exceptionValue is ExceptionInfoContext { IsErrorTemplate: true } excInfoTemplate)
-                {
-                    throw new ParametrizedRuntimeException(excInfoTemplate.Description, excInfoTemplate.Parameters);
-                }
-                else if (exceptionValue is ExceptionInfoContext { IsErrorTemplate: false } excInfo)
-                {
-                    throw new RuntimeException(excInfo.MessageWithoutCodeFragment, excInfo.ActualException());
-                }
+                if (exceptionValue is ExceptionInfoContext excInfo)
+                {
+                    if (excInfo.IsErrorTemplate)
+                    {
+                        throw CreateParametrizedRuntimeException(excInfo);
+                    }
+                    throw CreateRuntimeExceptionWithCause(excInfo);
+                }

Add these private methods:

private static ParametrizedRuntimeException CreateParametrizedRuntimeException(ExceptionInfoContext excInfo)
{
    return new ParametrizedRuntimeException(excInfo.Description, excInfo.Parameters);
}

private static RuntimeException CreateRuntimeExceptionWithCause(ExceptionInfoContext excInfo)
{
    return new RuntimeException(excInfo.MessageWithoutCodeFragment, excInfo.ActualException());
}
tests/global-funcs.os (1)

892-926: LGTM! The test provides good coverage of the new exception handling behavior.

The test effectively validates:

  • Initial exception throwing
  • Error information propagation
  • Re-throwing with preserved information

Consider adding these additional test cases:

  1. Nested exception handling (try-catch inside try-catch)
  2. Exception with empty or null parameters
  3. Exception with non-string parameters
  4. Multiple re-throws to verify deep propagation
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 985c65d and 07dbe5b.

📒 Files selected for processing (3)
  • src/ScriptEngine/Machine/Contexts/ExceptionInfoContext.cs (1 hunks)
  • src/ScriptEngine/Machine/MachineInstance.cs (1 hunks)
  • tests/global-funcs.os (2 hunks)
🔇 Additional comments (2)
src/ScriptEngine/Machine/Contexts/ExceptionInfoContext.cs (1)

Line range hint 54-65: LGTM! The change in visibility is necessary for enhanced error handling.

Making ActualException public allows external access to the underlying exception, which is essential for the improved error information propagation mechanism.

tests/global-funcs.os (1)

80-81: LGTM! Test registration is properly added.

The new test is correctly registered in the test list.

@sfaqer sfaqer changed the title Пробрасывание информации об ошибки через ВызватьИсключение Пробрасывание информации об ошибке через ВызватьИсключение Jan 14, 2025
юТест.ПроверитьИстину(ЗначениеЗаполнено(ИнформацияОбОшибке), "Исключение не было брошено");

Попытка
ВызватьИсключение ИнформацияОбОшибке;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Я не уверен, что это правильный API для этой функции. Давайте обсудим. @nixel2007 ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ну я это делал из соображений того что это не отрывает обратную совместимость, и в общем случае достаточно удобно в сценарии работы с фоновыми заданиями, типа:

	Дождались = Задание.ОжидатьЗавершения(Таймаут);

	Если Дождались И Задание.Состояние = СостояниеФоновогоЗадания.Завершено Тогда
		Возврат Задание.Результат;
	ИначеЕсли Не Дождались Тогда
		ВызватьИсключение "Превышено время ожидания получения результата";
	Иначе
		ВызватьИсключение Задание.ИнформацияОбОшибке;
	КонецЕсли;

Таким образом с помощью данной доработки, мы на верх по стеку во первых передали информацию о текущей ошибке со стеком текущего треда, так и внутрь положили причину с оригинальной информацией об ошибке из треда фонового задания, и со стеком треда фонового задания.

Если рассуждать в контексте API, то наверное можно сделать третий параметр конструктора шаблона информации об ошибке, типа:

Попытка
    ВызватьИсключение "Я вложенная ошибка";
Исключение
    ВызватьИсключение Новый ИнформацияОбОшибке("Я ошибка", Новый Массив, ИнформацияОбОшибке());
КонецПопытки

Но даже если добавить параметр Причина в конструктор, я бы всё равно голосовал за то что бы сохранить и то что есть в этом реквесте, т.к мне кажется что он дополняет контекст в части существующих сценариев обработки ошибок и не ломает обратную совместимость =)

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

я ожидал ВызватьИсключение Новый ИнформацияОбОшибке(), но действительно, если уже есть сохраненная информация, то дать возможность сделать ее re-throw тоже нужно

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Мне синтаксис с пробросом имеющейся переменной ИнформацияОбОшибке непонятен. Неясно, что выбрасывается. С Новый и параметром конструктора - все понятно

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

try {

} catch (Exception e) {
  log.error("ой ой", e);
  throw e;
} 

Тоже самое, не?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ну я выше расписал кейс с ФоновымЗданием, которое нам тоже не швыряет исключение, а приносит его в поле, как по другому сделать rethrow ИнформацииОбОшибке которая лежит в поле фонового задания?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

как по другому сделать rethrow ИнформацииОбОшибке которая лежит в поле фонового задания?

через Новый и вкладывание вероятно.

Но вы, раз ява-положительные, вы и скажите - такое правда норм, поймать в одном месте, записать e в переменную, передать в какой-то метод, а оттуда выбросить, как rethrow?

в переменную оно кладется просто в силу синтаксиса языка. передача в другой метод, наверное, не частая штука, но re-throw не из блока catch я и видел и сам писал.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Я вынес доработку по конструктору в отдельный PR: #1494 по нему я так понял концептуальных возражений нет

В рамках этого PR и текущего обсуждения надо решить будем ли мы давать возможность писать:

ВызватьИсключение ИнформацияОбОшибке;

Вместо

ВызватьИсключение Новый ИнформацияОбОшибке(ИнформацияОбОшибке.Описание, Новый Массив, ИнформацияОбОшибке);

Или это будет слишком диабетический сахар xD

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ну вот кейс с фоновым заданием и перевыбросом мне понятен. Теперь я согласен :)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Перебазировал на актуальный develop и актуализировал реализацию по доработкам по конструктору

…стве параметра, создаётся новая `ИнформацияОбОшибке` которая содержит оригинальную информацию об ошибке в поле `Причина`
@sfaqer sfaqer force-pushed the feature/excInfoRethrow branch from 07dbe5b to 3f7c479 Compare January 21, 2025 06:04
@EvilBeaver EvilBeaver merged commit fb12d30 into EvilBeaver:develop Jan 21, 2025
1 of 2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants