xref: /aosp_15_r20/external/pytorch/torch/csrc/api/include/torch/data/worker_exception.h (revision da0073e96a02ea20f0ac840b70461e3646d07c45)
1 #pragma once
2 
3 #include <exception>
4 #include <string>
5 #include <utility>
6 
7 namespace torch {
8 namespace data {
9 
10 /// An exception thrown when a DataLoader's worker thread throws an exception,
11 /// which is caught. A `WorkerException` stores an `exception_ptr` to the
12 /// original exception thrown in the worker thread.
13 struct WorkerException : public std::exception {
14   /// Constructs a `WorkerException` from an `exception_ptr`.
WorkerExceptionWorkerException15   explicit WorkerException(std::exception_ptr original)
16       : original_exception(std::move(original)),
17         message("Caught exception in DataLoader worker thread.") {
18     try {
19       std::rethrow_exception(original_exception);
20     } catch (std::exception& e) {
21       message += " Original message: ";
22       message += e.what();
23     }
24   }
25 
whatWorkerException26   const char* what() const noexcept override {
27     return message.c_str();
28   }
29 
30   /// The original exception thrown in the worker thread.
31   std::exception_ptr original_exception;
32 
33   /// This exception's message (not the original exception's message).
34   std::string message;
35 };
36 
37 } // namespace data
38 } // namespace torch
39