Skip to content

Conversation

@jo-elimu
Copy link
Member

Issue Number

Purpose

Technical Details

Testing Instructions

Screenshots


Format Checks

Note

Files in PRs are automatically checked for format violations with mvn spotless:check.

If this PR contains files with format violations, run mvn spotless:apply to fix them.

@jo-elimu jo-elimu self-assigned this Jun 24, 2025
@jo-elimu jo-elimu requested a review from a team as a code owner June 24, 2025 08:20
@jo-elimu jo-elimu requested review from SnehaHS65, Souvik-Cyclic and vrudas and removed request for a team June 24, 2025 08:20
@jo-elimu jo-elimu linked an issue Jun 24, 2025 that may be closed by this pull request
3 tasks
@codecov
Copy link

codecov bot commented Jun 24, 2025

Codecov Report

Attention: Patch coverage is 0% with 218 lines in your changes missing coverage. Please review.

Project coverage is 16.47%. Comparing base (edf84ee) to head (acba640).
Report is 6 commits behind head on main.

Files with missing lines Patch % Lines
...ts/StoryBookLearningEventsCsvExportController.java 0.00% 33 Missing ⚠️
...udents/VideoLearningEventsCsvExportController.java 0.00% 33 Missing ⚠️
...etterSoundAssessmentEventsCsvExportController.java 0.00% 32 Missing ⚠️
...dents/NumberLearningEventsCsvExportController.java 0.00% 31 Missing ⚠️
...dents/WordAssessmentEventsCsvExportController.java 0.00% 31 Missing ⚠️
...tudents/WordLearningEventsCsvExportController.java 0.00% 30 Missing ⚠️
.../LetterSoundLearningEventsCsvExportController.java 0.00% 28 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##               main    #2281      +/-   ##
============================================
- Coverage     16.49%   16.47%   -0.02%     
  Complexity      450      450              
============================================
  Files           254      254              
  Lines          7470     7477       +7     
  Branches        849      849              
============================================
  Hits           1232     1232              
- Misses         6173     6180       +7     
  Partials         65       65              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 24, 2025

Walkthrough

The code updates several analytics CSV export controllers to wrap their logic in try-catch blocks that handle all exceptions, not just IOExceptions. Upon any exception, an error message is logged and a notification is sent to a Discord analytics channel using DiscordHelper. No changes were made to method signatures or exported entities.

Changes

File(s) Change Summary
src/main/java/ai/elimu/web/analytics/students/LetterSoundAssessmentEventsCsvExportController.java
src/main/java/ai/elimu/web/analytics/students/LetterSoundLearningEventsCsvExportController.java
src/main/java/ai/elimu/web/analytics/students/NumberLearningEventsCsvExportController.java
src/main/java/ai/elimu/web/analytics/students/StoryBookLearningEventsCsvExportController.java
src/main/java/ai/elimu/web/analytics/students/VideoLearningEventsCsvExportController.java
src/main/java/ai/elimu/web/analytics/students/WordAssessmentEventsCsvExportController.java
src/main/java/ai/elimu/web/analytics/students/WordLearningEventsCsvExportController.java
Wrapped CSV export logic in try-catch blocks catching all exceptions; added Discord analytics channel notification on error; updated imports.
pom-dependency-tree.txt Updated project artifact version from 2.6.76-SNAPSHOT to 2.6.78-SNAPSHOT.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Controller
    participant DiscordHelper

    User->>Controller: HTTP request for CSV export
    Controller->>Controller: Process CSV export logic
    alt Success
        Controller->>User: Return CSV file
    else Exception occurs
        Controller->>DiscordHelper: postToChannel(Channel.ANALYTICS, error message)
        Controller->>User: Log error, return error response
    end
Loading

Assessment against linked issues

Objective Addressed Explanation
Add Discord notification (#2280)
Handle NullPointer exception (#2280)
Add regression test (#2280) No regression tests were added in the code changes.

Possibly related PRs

Suggested reviewers

  • SnehaHS65
  • AshishBagdane
  • Souvik-Cyclic
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @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
Contributor

@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: 3

🔭 Outside diff range comments (1)
src/main/java/ai/elimu/web/analytics/students/WordAssessmentEventsCsvExportController.java (1)

34-38: Fix method signature inconsistency and improve error handling.

The method signature declares throws IOException but the catch block now handles all exceptions without re-throwing them, breaking the method contract. Additionally, when errors occur, clients receive no HTTP error response.

Apply this diff to fix the issues:

  public void handleRequest(
      @PathVariable Long studentId,
      HttpServletResponse response,
      OutputStream outputStream
- ) throws IOException {
+ ) {
    // ... existing code ...
    } catch (Exception ex) {
-     log.error(ex.getMessage());
+     log.error("Error during CSV export of word assessment events", ex);
+     response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      DiscordHelper.postToChannel(Channel.ANALYTICS, "Error during CSV export of word assessment events: `" + ex.getClass() + ": " + ex.getMessage() + "`");
    }

Also applies to: 89-92

♻️ Duplicate comments (3)
src/main/java/ai/elimu/web/analytics/students/NumberLearningEventsCsvExportController.java (1)

34-38: Apply the same fixes as WordAssessmentEventsCsvExportController.

This controller has identical issues: method signature inconsistency and missing client error response.

Reference the fix suggested in WordAssessmentEventsCsvExportController.java lines 34-38,89-92.

Also applies to: 89-92

src/main/java/ai/elimu/web/analytics/students/WordLearningEventsCsvExportController.java (1)

34-38: Apply consistent error handling fixes.

This controller has the same method signature and error response issues as the other controllers in this PR.

Apply the same fixes suggested for WordAssessmentEventsCsvExportController.java lines 34-38,89-92.

Also applies to: 88-91

src/main/java/ai/elimu/web/analytics/students/StoryBookLearningEventsCsvExportController.java (1)

35-39: Apply consistent error handling improvements.

This controller has the same method signature and error response issues as the other controllers.

Apply the same fixes suggested for WordAssessmentEventsCsvExportController.java lines 34-38,89-92.

Also applies to: 91-94

🧹 Nitpick comments (2)
src/main/java/ai/elimu/web/analytics/students/WordAssessmentEventsCsvExportController.java (1)

89-92: Consider more specific exception handling.

Catching all Exception types is very broad and might mask programming errors. Consider catching specific exceptions like IOException, SQLException, or creating custom exceptions for different failure scenarios.

Example approach:

- } catch (Exception ex) {
+ } catch (IOException | SQLException ex) {
    log.error("Error during CSV export of word assessment events", ex);
    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    DiscordHelper.postToChannel(Channel.ANALYTICS, "Error during CSV export of word assessment events: `" + ex.getClass() + ": " + ex.getMessage() + "`");
+ } catch (Exception ex) {
+   log.error("Unexpected error during CSV export", ex);
+   response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+   DiscordHelper.postToChannel(Channel.ANALYTICS, "Unexpected error during CSV export: `" + ex.getClass() + ": " + ex.getMessage() + "`");
src/main/java/ai/elimu/web/analytics/students/LetterSoundLearningEventsCsvExportController.java (1)

56-57: Consider removing or documenting the commented code.

The commented-out code for letter_sound_letters and letter_sound_sounds fields suggests these were intentionally excluded from the CSV export. Consider either:

  1. Removing the commented code if these fields are permanently excluded
  2. Adding a comment explaining why these fields are excluded
  3. Converting to a TODO comment if they should be included in the future
-              // "letter_sound_letters",
-              // "letter_sound_sounds",
+              // TODO: Exclude letter_sound_letters and letter_sound_sounds for privacy reasons

Also applies to: 71-72

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e03982e and acba640.

📒 Files selected for processing (8)
  • pom-dependency-tree.txt (1 hunks)
  • src/main/java/ai/elimu/web/analytics/students/LetterSoundAssessmentEventsCsvExportController.java (2 hunks)
  • src/main/java/ai/elimu/web/analytics/students/LetterSoundLearningEventsCsvExportController.java (2 hunks)
  • src/main/java/ai/elimu/web/analytics/students/NumberLearningEventsCsvExportController.java (2 hunks)
  • src/main/java/ai/elimu/web/analytics/students/StoryBookLearningEventsCsvExportController.java (2 hunks)
  • src/main/java/ai/elimu/web/analytics/students/VideoLearningEventsCsvExportController.java (2 hunks)
  • src/main/java/ai/elimu/web/analytics/students/WordAssessmentEventsCsvExportController.java (2 hunks)
  • src/main/java/ai/elimu/web/analytics/students/WordLearningEventsCsvExportController.java (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (12)
  • GitHub Check: test_rest
  • GitHub Check: test_rest
  • GitHub Check: test_rest
  • GitHub Check: test_rest
  • GitHub Check: test_rest
  • GitHub Check: build (windows-latest, 21)
  • GitHub Check: build (ubuntu-latest, 17)
  • GitHub Check: build (macos-latest, 21)
  • GitHub Check: build (windows-latest, 17)
  • GitHub Check: build (ubuntu-latest, 21)
  • GitHub Check: build (macos-latest, 17)
  • GitHub Check: test_rest
🔇 Additional comments (9)
pom-dependency-tree.txt (1)

1-1: Version bump looks appropriate.

The version update from 2.6.76-SNAPSHOT to 2.6.78-SNAPSHOT aligns with the enhancement being made to CSV export error handling.

src/main/java/ai/elimu/web/analytics/students/WordAssessmentEventsCsvExportController.java (1)

7-8: LGTM: Clean import additions for Discord integration.

The imports for DiscordHelper and Channel are properly added to support the error notification functionality.

src/main/java/ai/elimu/web/analytics/students/NumberLearningEventsCsvExportController.java (1)

7-8: LGTM: Consistent import pattern.

The DiscordHelper imports are correctly added, maintaining consistency with other controllers.

src/main/java/ai/elimu/web/analytics/students/WordLearningEventsCsvExportController.java (1)

7-8: LGTM: Consistent import additions.

The DiscordHelper imports follow the same pattern as other controllers in this PR.

src/main/java/ai/elimu/web/analytics/students/StoryBookLearningEventsCsvExportController.java (2)

8-9: LGTM: Consistent import structure.

The DiscordHelper imports maintain the same pattern established in other controllers.


48-50: Good: Android ID redaction is protected by error handling.

The Android ID redaction logic is correctly placed within the try block, ensuring that any exceptions during this process are caught and reported.

src/main/java/ai/elimu/web/analytics/students/VideoLearningEventsCsvExportController.java (1)

8-9: LGTM: Clean import additions for Discord integration.

The imports for DiscordHelper and DiscordHelper.Channel are properly added to support the new error notification feature.

src/main/java/ai/elimu/web/analytics/students/LetterSoundAssessmentEventsCsvExportController.java (1)

7-8: LGTM: Proper imports for Discord functionality.

The Discord helper imports are correctly added.

src/main/java/ai/elimu/web/analytics/students/LetterSoundLearningEventsCsvExportController.java (1)

7-8: LGTM: Discord imports properly added.

The necessary imports for Discord error reporting are correctly included.

Comment on lines +43 to 95
try {
Student student = studentDao.read(studentId);
log.info("student.getAndroidId(): " + student.getAndroidId());

List<VideoLearningEvent> videoLearningEvents = videoLearningEventDao.readAll(student.getAndroidId());
log.info("videoLearningEvents.size(): " + videoLearningEvents.size());
for (VideoLearningEvent videoLearningEvent : videoLearningEvents) {
videoLearningEvent.setAndroidId(AnalyticsHelper.redactAndroidId(videoLearningEvent.getAndroidId()));
}
List<VideoLearningEvent> videoLearningEvents = videoLearningEventDao.readAll(student.getAndroidId());
log.info("videoLearningEvents.size(): " + videoLearningEvents.size());
for (VideoLearningEvent videoLearningEvent : videoLearningEvents) {
videoLearningEvent.setAndroidId(AnalyticsHelper.redactAndroidId(videoLearningEvent.getAndroidId()));
}

CSVFormat csvFormat = CSVFormat.DEFAULT.builder()
.setHeader(
"id",
"timestamp",
"package_name",
"learning_event_type",
"additional_data",
"research_experiment",
"experiment_group",
"video_title",
"video_id"
).build();
StringWriter stringWriter = new StringWriter();
CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat);
for (VideoLearningEvent videoLearningEvent : videoLearningEvents) {
log.info("videoLearningEvent.getId(): " + videoLearningEvent.getId());
csvPrinter.printRecord(
videoLearningEvent.getId(),
videoLearningEvent.getTimestamp().getTimeInMillis() / 1_000,
videoLearningEvent.getPackageName(),
videoLearningEvent.getLearningEventType(),
videoLearningEvent.getAdditionalData(),
videoLearningEvent.getResearchExperiment().ordinal(),
videoLearningEvent.getExperimentGroup().ordinal(),
videoLearningEvent.getVideoTitle(),
videoLearningEvent.getVideoId()
);
}
csvPrinter.flush();
csvPrinter.close();
CSVFormat csvFormat = CSVFormat.DEFAULT.builder()
.setHeader(
"id",
"timestamp",
"package_name",
"learning_event_type",
"additional_data",
"research_experiment",
"experiment_group",
"video_title",
"video_id"
).build();
StringWriter stringWriter = new StringWriter();
CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat);
for (VideoLearningEvent videoLearningEvent : videoLearningEvents) {
log.info("videoLearningEvent.getId(): " + videoLearningEvent.getId());
csvPrinter.printRecord(
videoLearningEvent.getId(),
videoLearningEvent.getTimestamp().getTimeInMillis() / 1_000,
videoLearningEvent.getPackageName(),
videoLearningEvent.getLearningEventType(),
videoLearningEvent.getAdditionalData(),
videoLearningEvent.getResearchExperiment().ordinal(),
videoLearningEvent.getExperimentGroup().ordinal(),
videoLearningEvent.getVideoTitle(),
videoLearningEvent.getVideoId()
);
}
csvPrinter.flush();
csvPrinter.close();

String csvFileContent = stringWriter.toString();
response.setContentType("text/csv");
byte[] bytes = csvFileContent.getBytes();
response.setContentLength(bytes.length);
try {
String csvFileContent = stringWriter.toString();
response.setContentType("text/csv");
byte[] bytes = csvFileContent.getBytes();
response.setContentLength(bytes.length);
outputStream.write(bytes);
outputStream.flush();
outputStream.close();
} catch (IOException ex) {
} catch (Exception ex) {
log.error(ex.getMessage());
DiscordHelper.postToChannel(Channel.ANALYTICS, "Error during CSV export of video learning events: `" + ex.getClass() + ": " + ex.getMessage() + "`");
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Review exception handling and HTTP response management.

While the Discord error notification is a good addition, there are several concerns with the current implementation:

  1. Overly broad exception handling: Catching Exception may mask programming errors that should be addressed rather than silently logged.

  2. HTTP response state: When an exception occurs, no HTTP response content is written, potentially leaving clients with an incomplete or confusing response.

  3. Potential information disclosure: The Discord message exposes exception class names and messages, which could contain sensitive information.

Consider this improved approach:

-    } catch (Exception ex) {
-      log.error(ex.getMessage());
-      DiscordHelper.postToChannel(Channel.ANALYTICS, "Error during CSV export of video learning events: `" + ex.getClass() + ": " + ex.getMessage() + "`");
+    } catch (Exception ex) {
+      log.error("Error during CSV export of video learning events for studentId: " + studentId, ex);
+      
+      // Send error response to client
+      response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+      response.setContentType("text/plain");
+      try {
+        outputStream.write("Internal server error occurred during CSV export".getBytes());
+        outputStream.flush();
+      } catch (IOException ioEx) {
+        log.error("Failed to write error response", ioEx);
+      }
+      
+      // Sanitize error message for Discord
+      String sanitizedMessage = "Error during CSV export of video learning events for student " + studentId + ": " + ex.getClass().getSimpleName();
+      DiscordHelper.postToChannel(Channel.ANALYTICS, sanitizedMessage);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try {
Student student = studentDao.read(studentId);
log.info("student.getAndroidId(): " + student.getAndroidId());
List<VideoLearningEvent> videoLearningEvents = videoLearningEventDao.readAll(student.getAndroidId());
log.info("videoLearningEvents.size(): " + videoLearningEvents.size());
for (VideoLearningEvent videoLearningEvent : videoLearningEvents) {
videoLearningEvent.setAndroidId(AnalyticsHelper.redactAndroidId(videoLearningEvent.getAndroidId()));
}
List<VideoLearningEvent> videoLearningEvents = videoLearningEventDao.readAll(student.getAndroidId());
log.info("videoLearningEvents.size(): " + videoLearningEvents.size());
for (VideoLearningEvent videoLearningEvent : videoLearningEvents) {
videoLearningEvent.setAndroidId(AnalyticsHelper.redactAndroidId(videoLearningEvent.getAndroidId()));
}
CSVFormat csvFormat = CSVFormat.DEFAULT.builder()
.setHeader(
"id",
"timestamp",
"package_name",
"learning_event_type",
"additional_data",
"research_experiment",
"experiment_group",
"video_title",
"video_id"
).build();
StringWriter stringWriter = new StringWriter();
CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat);
for (VideoLearningEvent videoLearningEvent : videoLearningEvents) {
log.info("videoLearningEvent.getId(): " + videoLearningEvent.getId());
csvPrinter.printRecord(
videoLearningEvent.getId(),
videoLearningEvent.getTimestamp().getTimeInMillis() / 1_000,
videoLearningEvent.getPackageName(),
videoLearningEvent.getLearningEventType(),
videoLearningEvent.getAdditionalData(),
videoLearningEvent.getResearchExperiment().ordinal(),
videoLearningEvent.getExperimentGroup().ordinal(),
videoLearningEvent.getVideoTitle(),
videoLearningEvent.getVideoId()
);
}
csvPrinter.flush();
csvPrinter.close();
CSVFormat csvFormat = CSVFormat.DEFAULT.builder()
.setHeader(
"id",
"timestamp",
"package_name",
"learning_event_type",
"additional_data",
"research_experiment",
"experiment_group",
"video_title",
"video_id"
).build();
StringWriter stringWriter = new StringWriter();
CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat);
for (VideoLearningEvent videoLearningEvent : videoLearningEvents) {
log.info("videoLearningEvent.getId(): " + videoLearningEvent.getId());
csvPrinter.printRecord(
videoLearningEvent.getId(),
videoLearningEvent.getTimestamp().getTimeInMillis() / 1_000,
videoLearningEvent.getPackageName(),
videoLearningEvent.getLearningEventType(),
videoLearningEvent.getAdditionalData(),
videoLearningEvent.getResearchExperiment().ordinal(),
videoLearningEvent.getExperimentGroup().ordinal(),
videoLearningEvent.getVideoTitle(),
videoLearningEvent.getVideoId()
);
}
csvPrinter.flush();
csvPrinter.close();
String csvFileContent = stringWriter.toString();
response.setContentType("text/csv");
byte[] bytes = csvFileContent.getBytes();
response.setContentLength(bytes.length);
try {
String csvFileContent = stringWriter.toString();
response.setContentType("text/csv");
byte[] bytes = csvFileContent.getBytes();
response.setContentLength(bytes.length);
outputStream.write(bytes);
outputStream.flush();
outputStream.close();
} catch (IOException ex) {
} catch (Exception ex) {
log.error(ex.getMessage());
DiscordHelper.postToChannel(Channel.ANALYTICS, "Error during CSV export of video learning events: `" + ex.getClass() + ": " + ex.getMessage() + "`");
}
try {
// … existing try block unchanged …
outputStream.write(bytes);
outputStream.flush();
outputStream.close();
} catch (Exception ex) {
// Improved logging with full stacktrace and context
log.error("Error during CSV export of video learning events for studentId: " + studentId, ex);
// Send a proper HTTP 500 response to the client
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.setContentType("text/plain");
try {
outputStream.write("Internal server error occurred during CSV export".getBytes());
outputStream.flush();
} catch (IOException ioEx) {
log.error("Failed to write error response", ioEx);
}
// Sanitize and send a concise error notification to Discord
String sanitizedMessage =
"Error during CSV export of video learning events for student "
+ studentId
+ ": "
+ ex.getClass().getSimpleName();
DiscordHelper.postToChannel(Channel.ANALYTICS, sanitizedMessage);
}
🤖 Prompt for AI Agents
In
src/main/java/ai/elimu/web/analytics/students/VideoLearningEventsCsvExportController.java
between lines 43 and 95, the current exception handling is too broad by catching
Exception, which can hide programming errors. Refine the catch block to handle
more specific exceptions where possible. Additionally, ensure that when an
exception occurs, a proper HTTP error response with an appropriate status code
and a generic error message is sent to the client to avoid leaving the response
incomplete. Finally, modify the Discord error notification to avoid exposing
sensitive exception details by logging only a generic error message or sanitized
information instead of full exception class names and messages.

Comment on lines +41 to 94
try {
Student student = studentDao.read(studentId);
log.info("student.getAndroidId(): " + student.getAndroidId());

List<LetterSoundAssessmentEvent> letterSoundAssessmentEvents = letterSoundAssessmentEventDao.readAll(student.getAndroidId());
log.info("letterSoundAssessmentEvents.size(): " + letterSoundAssessmentEvents.size());
List<LetterSoundAssessmentEvent> letterSoundAssessmentEvents = letterSoundAssessmentEventDao.readAll(student.getAndroidId());
log.info("letterSoundAssessmentEvents.size(): " + letterSoundAssessmentEvents.size());

CSVFormat csvFormat = CSVFormat.DEFAULT.builder()
.setHeader(
"id",
"timestamp",
"package_name",
"mastery_score",
"time_spent_ms",
"additional_data",
"research_experiment",
"experiment_group",
"letter_sound_letters",
"letter_sound_sounds",
"letter_sound_id"
).build();
StringWriter stringWriter = new StringWriter();
CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat);
for (LetterSoundAssessmentEvent letterSoundAssessmentEvent : letterSoundAssessmentEvents) {
log.info("letterSoundAssessmentEvent.getId(): " + letterSoundAssessmentEvent.getId());
csvPrinter.printRecord(
letterSoundAssessmentEvent.getId(),
letterSoundAssessmentEvent.getTimestamp().getTimeInMillis() / 1_000,
letterSoundAssessmentEvent.getPackageName(),
letterSoundAssessmentEvent.getMasteryScore(),
letterSoundAssessmentEvent.getTimeSpentMs(),
letterSoundAssessmentEvent.getAdditionalData(),
letterSoundAssessmentEvent.getResearchExperiment().ordinal(),
letterSoundAssessmentEvent.getExperimentGroup().ordinal(),
letterSoundAssessmentEvent.getLetterSoundLetters(),
letterSoundAssessmentEvent.getLetterSoundSounds(),
letterSoundAssessmentEvent.getLetterSoundId()
);
}
csvPrinter.flush();
csvPrinter.close();
CSVFormat csvFormat = CSVFormat.DEFAULT.builder()
.setHeader(
"id",
"timestamp",
"package_name",
"mastery_score",
"time_spent_ms",
"additional_data",
"research_experiment",
"experiment_group",
"letter_sound_letters",
"letter_sound_sounds",
"letter_sound_id"
).build();
StringWriter stringWriter = new StringWriter();
CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat);
for (LetterSoundAssessmentEvent letterSoundAssessmentEvent : letterSoundAssessmentEvents) {
log.info("letterSoundAssessmentEvent.getId(): " + letterSoundAssessmentEvent.getId());
csvPrinter.printRecord(
letterSoundAssessmentEvent.getId(),
letterSoundAssessmentEvent.getTimestamp().getTimeInMillis() / 1_000,
letterSoundAssessmentEvent.getPackageName(),
letterSoundAssessmentEvent.getMasteryScore(),
letterSoundAssessmentEvent.getTimeSpentMs(),
letterSoundAssessmentEvent.getAdditionalData(),
letterSoundAssessmentEvent.getResearchExperiment().ordinal(),
letterSoundAssessmentEvent.getExperimentGroup().ordinal(),
letterSoundAssessmentEvent.getLetterSoundLetters(),
letterSoundAssessmentEvent.getLetterSoundSounds(),
letterSoundAssessmentEvent.getLetterSoundId()
);
}
csvPrinter.flush();
csvPrinter.close();

String csvFileContent = stringWriter.toString();
response.setContentType("text/csv");
byte[] bytes = csvFileContent.getBytes();
response.setContentLength(bytes.length);
try {
String csvFileContent = stringWriter.toString();
response.setContentType("text/csv");
byte[] bytes = csvFileContent.getBytes();
response.setContentLength(bytes.length);
outputStream.write(bytes);
outputStream.flush();
outputStream.close();
} catch (IOException ex) {
} catch (Exception ex) {
log.error(ex.getMessage());
DiscordHelper.postToChannel(Channel.ANALYTICS, "Error during CSV export of letter-sound assessment events: `" + ex.getClass() + ": " + ex.getMessage() + "`");
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Same exception handling concerns as VideoLearningEventsCsvExportController.

This implementation has identical issues to the VideoLearningEventsCsvExportController:

  1. Overly broad exception catching that may hide programming errors
  2. No HTTP error response sent to clients when exceptions occur
  3. Potential information leakage in Discord error messages

Apply the same improvements suggested for VideoLearningEventsCsvExportController:

-    } catch (Exception ex) {
-      log.error(ex.getMessage());
-      DiscordHelper.postToChannel(Channel.ANALYTICS, "Error during CSV export of letter-sound assessment events: `" + ex.getClass() + ": " + ex.getMessage() + "`");
+    } catch (Exception ex) {
+      log.error("Error during CSV export of letter-sound assessment events for studentId: " + studentId, ex);
+      
+      response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+      response.setContentType("text/plain");
+      try {
+        outputStream.write("Internal server error occurred during CSV export".getBytes());
+        outputStream.flush();
+      } catch (IOException ioEx) {
+        log.error("Failed to write error response", ioEx);
+      }
+      
+      String sanitizedMessage = "Error during CSV export of letter-sound assessment events for student " + studentId + ": " + ex.getClass().getSimpleName();
+      DiscordHelper.postToChannel(Channel.ANALYTICS, sanitizedMessage);
🤖 Prompt for AI Agents
In
src/main/java/ai/elimu/web/analytics/students/LetterSoundAssessmentEventsCsvExportController.java
between lines 41 and 94, the exception handling is too broad, catching all
exceptions without distinguishing error types, does not send an appropriate HTTP
error response to the client, and posts detailed exception information to
Discord which may leak sensitive data. Refactor the catch block to catch more
specific exceptions where possible, send a proper HTTP error status and message
in the response to inform the client of the failure, and sanitize or limit the
error details posted to Discord to avoid exposing sensitive internal
information.

Comment on lines +41 to 90
try {
Student student = studentDao.read(studentId);
log.info("student.getAndroidId(): " + student.getAndroidId());

List<LetterSoundLearningEvent> letterSoundLearningEvents = letterSoundLearningEventDao.readAll(student.getAndroidId());
log.info("letterSoundLearningEvents.size(): " + letterSoundLearningEvents.size());
List<LetterSoundLearningEvent> letterSoundLearningEvents = letterSoundLearningEventDao.readAll(student.getAndroidId());
log.info("letterSoundLearningEvents.size(): " + letterSoundLearningEvents.size());

CSVFormat csvFormat = CSVFormat.DEFAULT.builder()
.setHeader(
"id",
"timestamp",
"package_name",
"additional_data",
"research_experiment",
"experiment_group",
// "letter_sound_letters",
// "letter_sound_sounds",
"letter_sound_id"
).build();
StringWriter stringWriter = new StringWriter();
CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat);
for (LetterSoundLearningEvent letterSoundLearningEvent : letterSoundLearningEvents) {
log.info("letterSoundLearningEvent.getId(): " + letterSoundLearningEvent.getId());
csvPrinter.printRecord(
letterSoundLearningEvent.getId(),
letterSoundLearningEvent.getTimestamp().getTimeInMillis() / 1_000,
letterSoundLearningEvent.getPackageName(),
letterSoundLearningEvent.getAdditionalData(),
letterSoundLearningEvent.getResearchExperiment().ordinal(),
letterSoundLearningEvent.getExperimentGroup().ordinal(),
// letterSoundLearningEvent.getLetterSoundLetters(),
// letterSoundLearningEvent.getLetterSoundSounds(),
letterSoundLearningEvent.getLetterSoundId()
);
}
csvPrinter.flush();
csvPrinter.close();
CSVFormat csvFormat = CSVFormat.DEFAULT.builder()
.setHeader(
"id",
"timestamp",
"package_name",
"additional_data",
"research_experiment",
"experiment_group",
// "letter_sound_letters",
// "letter_sound_sounds",
"letter_sound_id"
).build();
StringWriter stringWriter = new StringWriter();
CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat);
for (LetterSoundLearningEvent letterSoundLearningEvent : letterSoundLearningEvents) {
log.info("letterSoundLearningEvent.getId(): " + letterSoundLearningEvent.getId());
csvPrinter.printRecord(
letterSoundLearningEvent.getId(),
letterSoundLearningEvent.getTimestamp().getTimeInMillis() / 1_000,
letterSoundLearningEvent.getPackageName(),
letterSoundLearningEvent.getAdditionalData(),
letterSoundLearningEvent.getResearchExperiment().ordinal(),
letterSoundLearningEvent.getExperimentGroup().ordinal(),
// letterSoundLearningEvent.getLetterSoundLetters(),
// letterSoundLearningEvent.getLetterSoundSounds(),
letterSoundLearningEvent.getLetterSoundId()
);
}
csvPrinter.flush();
csvPrinter.close();

String csvFileContent = stringWriter.toString();
response.setContentType("text/csv");
byte[] bytes = csvFileContent.getBytes();
response.setContentLength(bytes.length);

String csvFileContent = stringWriter.toString();
response.setContentType("text/csv");
byte[] bytes = csvFileContent.getBytes();
response.setContentLength(bytes.length);
try {
outputStream.write(bytes);
outputStream.flush();
outputStream.close();
} catch (IOException ex) {
} catch (Exception ex) {
log.error(ex.getMessage());
DiscordHelper.postToChannel(Channel.ANALYTICS, "Error during CSV export of letter-sound learning events: `" + ex.getClass() + ": " + ex.getMessage() + "`");
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Identical exception handling issues as other controllers.

This controller has the same problematic exception handling pattern as the other two CSV export controllers:

  1. Catching all exceptions may mask important programming errors
  2. No proper HTTP error response for clients
  3. Potential information disclosure in Discord messages

For consistency across all CSV export controllers, apply the same error handling improvements:

-    } catch (Exception ex) {
-      log.error(ex.getMessage());
-      DiscordHelper.postToChannel(Channel.ANALYTICS, "Error during CSV export of letter-sound learning events: `" + ex.getClass() + ": " + ex.getMessage() + "`");
+    } catch (Exception ex) {
+      log.error("Error during CSV export of letter-sound learning events for studentId: " + studentId, ex);
+      
+      response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+      response.setContentType("text/plain");
+      try {
+        outputStream.write("Internal server error occurred during CSV export".getBytes());
+        outputStream.flush();
+      } catch (IOException ioEx) {
+        log.error("Failed to write error response", ioEx);
+      }
+      
+      String sanitizedMessage = "Error during CSV export of letter-sound learning events for student " + studentId + ": " + ex.getClass().getSimpleName();
+      DiscordHelper.postToChannel(Channel.ANALYTICS, sanitizedMessage);
🤖 Prompt for AI Agents
In
src/main/java/ai/elimu/web/analytics/students/LetterSoundLearningEventsCsvExportController.java
around lines 41 to 90, the current exception handling catches all exceptions
broadly, logs only the message, sends potentially sensitive error details to
Discord, and does not set an appropriate HTTP error response. To fix this,
narrow the exception handling to catch only expected exceptions, log full stack
traces for debugging, avoid sending detailed error information to Discord to
prevent information disclosure, and set a proper HTTP error status code and
message in the response to inform clients of the failure.

@jo-elimu jo-elimu merged commit 0a4f4d5 into main Jun 24, 2025
19 of 20 checks passed
@jo-elimu jo-elimu deleted the 2280-post-error-to-discord branch June 24, 2025 08:28
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.

Exception during CSV export

2 participants