2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2011,2012,2013,2014,2015,2016,2017, by the GROMACS development team, led by
5 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6 * and including many others, as listed in the AUTHORS file in the
7 * top-level source directory and at http://www.gromacs.org.
9 * GROMACS is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public License
11 * as published by the Free Software Foundation; either version 2.1
12 * of the License, or (at your option) any later version.
14 * GROMACS is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with GROMACS; if not, see
21 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 * If you want to redistribute modifications to GROMACS, please
25 * consider that scientific software is very special. Version
26 * control is crucial - bugs must be traceable. We will be happy to
27 * consider code for inclusion in the official distribution, but
28 * derived work must not be called official GROMACS. Details are found
29 * in the README & COPYING files - if they are missing, get the
30 * official version at http://www.gromacs.org.
32 * To help us fund GROMACS development, we humbly ask that you cite
33 * the research papers on the package. Check out http://www.gromacs.org.
37 * Implements classes and functions in exceptions.h.
39 * \author Teemu Murtola <teemu.murtola@gmail.com>
40 * \ingroup module_utility
44 #include "exceptions.h"
54 #include "thread_mpi/system_error.h"
56 #include "gromacs/utility/basenetwork.h"
57 #include "gromacs/utility/errorcodes.h"
58 #include "gromacs/utility/fatalerror.h"
59 #include "gromacs/utility/gmxassert.h"
60 #include "gromacs/utility/stringutil.h"
61 #include "gromacs/utility/textwriter.h"
63 #include "errorformat.h"
71 IExceptionInfo::~IExceptionInfo()
78 std::map<std::type_index, ExceptionInfoPointer> infos_;
81 } // namespace internal
86 /********************************************************************
91 * Error message or error context text item.
93 * Error messages for an exception are represented as a chain of ErrorMessage
94 * objects: the elements at the bottom of the chain (with no children) is the
95 * error message, and other elements are the context strings added.
97 * \ingroup module_utility
103 * Creates an error message object with the specified text.
105 * \param[in] text Text for the message.
107 explicit ErrorMessage(const std::string &text);
109 //! Whether this object is a context string.
110 bool isContext() const { return static_cast<bool>(child_); }
111 //! Returns the text for this object.
112 const std::string &text() const { return text_; }
114 * Returns the child object for a context object.
116 * Must not be called if isContext() returns false.
118 const ErrorMessage &child() const
120 GMX_ASSERT(isContext(),
121 "Attempting to access nonexistent message object");
126 * Creates a new message object with context prepended.
128 * \param[in] context Context string to add.
129 * \returns New error message object that has \p context as its text
130 * and \c this as its child.
131 * \throws std::bad_alloc if out of memory.
133 ErrorMessage prependContext(const std::string &context) const;
137 std::shared_ptr<ErrorMessage> child_;
141 * Stores a reason or the top-most context string of an exception.
143 * \ingroup module_utility
145 typedef ExceptionInfo<struct ExceptionInfoMessage_, ErrorMessage>
146 ExceptionInfoMessage;
148 ErrorMessage::ErrorMessage(const std::string &text)
151 size_t length = text_.find_last_not_of(" \n");
152 if (length == std::string::npos)
154 length = text_.length() - 1;
156 text_.resize(length + 1);
160 ErrorMessage::prependContext(const std::string &context) const
162 ErrorMessage newMessage(context);
163 newMessage.child_.reset(new ErrorMessage(*this));
168 * Stores list of nested exceptions for Gromacs exceptions.
170 * \ingroup module_utility
172 typedef ExceptionInfo<struct ExceptionInfoNestedExceptions_, internal::NestedExceptionList>
173 ExceptionInfoNestedExceptions;
177 /********************************************************************
181 GromacsException::GromacsException(const ExceptionInitializer &details)
182 : data_(new internal::ExceptionData)
184 setInfo(ExceptionInfoMessage(ErrorMessage(details.reason_)));
185 if (details.hasNestedExceptions())
187 setInfo(ExceptionInfoNestedExceptions(details.nested_));
191 const char *GromacsException::what() const noexcept
193 const ErrorMessage *msg = getInfo<ExceptionInfoMessage>();
196 return "No reason provided";
198 while (msg->isContext())
202 return msg->text().c_str();
205 void GromacsException::prependContext(const std::string &context)
207 const ErrorMessage *msg = getInfo<ExceptionInfoMessage>();
208 GMX_RELEASE_ASSERT(msg != nullptr, "Message should always be set");
209 setInfo(ExceptionInfoMessage(msg->prependContext(context)));
212 const internal::IExceptionInfo *
213 GromacsException::getInfo(const std::type_index &index) const
215 auto iter = data_->infos_.find(index);
216 if (iter != data_->infos_.end())
218 return iter->second.get();
223 void GromacsException::setInfo(
224 const std::type_index &index, internal::ExceptionInfoPointer &&item)
226 data_->infos_[index] = std::move(item);
229 /********************************************************************
230 * Derived exception classes
233 int FileIOError::errorCode() const
238 int InvalidInputError::errorCode() const
240 return eeInvalidInput;
243 int InconsistentInputError::errorCode() const
245 return eeInconsistentInput;
248 int ToleranceError::errorCode() const
253 int SimulationInstabilityError::errorCode() const
255 return eeInstability;
258 int InternalError::errorCode() const
260 return eeInternalError;
263 int APIError::errorCode() const
268 int RangeError::errorCode() const
273 int NotImplementedError::errorCode() const
275 return eeNotImplemented;
279 /********************************************************************
286 //! \addtogroup module_utility
290 * Abstracts actual output from the other logic in exception formatting.
292 * Object that implements this interface is passed to
293 * formatExceptionMessageInternal(), and is responsible for composing the
294 * output. This allows using the same implementation of interpreting the
295 * exceptions while still supporting output to different formats (e.g., to a
296 * string or to \c stderr).
301 virtual ~IMessageWriter() {}
304 * Writes a single line of text into the output.
306 * \param[in] text Text to write on the line.
307 * \param[in] indent Suggested number of spaces to indent the line.
309 virtual void writeLine(const char *text, int indent) = 0;
311 * Writes information about a system error (errno-based).
313 * \param[in] errorNumber errno value
314 * \param[in] funcName Name of the system call (can be NULL).
315 * \param[in] indent Suggested number of spaces to indent the output.
317 virtual void writeErrNoInfo(int errorNumber, const char *funcName,
322 * Exception information writer for cases where exceptions should be avoided.
324 * Formats the messages into the provided FILE handle without checking for
325 * errors in std::fprintf() calls.
327 class MessageWriterFileNoThrow : public IMessageWriter
330 //! Initializes a writer that writes to the given file handle.
331 explicit MessageWriterFileNoThrow(FILE *fp) : fp_(fp) {}
333 virtual void writeLine(const char *text, int indent)
335 internal::printFatalErrorMessageLine(fp_, text, indent);
337 virtual void writeErrNoInfo(int errorNumber, const char *funcName,
340 std::fprintf(fp_, "%*sReason: %s\n", indent, "",
341 std::strerror(errorNumber));
342 if (funcName != nullptr)
344 std::fprintf(fp_, "%*s(call to %s() returned error code %d)\n",
345 indent, "", funcName, errorNumber);
354 * Exception information writer to format into a TextOutputStream.
356 class MessageWriterTextWriter : public IMessageWriter
359 //! Initializes a writer that writes to the given stream.
360 explicit MessageWriterTextWriter(TextWriter *writer) : writer_(writer)
364 virtual void writeLine(const char *text, int indent)
366 writer_->wrapperSettings().setIndent(indent);
367 writer_->writeLine(text);
369 virtual void writeErrNoInfo(int errorNumber, const char *funcName,
372 writer_->wrapperSettings().setIndent(indent);
373 writer_->writeLine(formatString("Reason: %s", std::strerror(errorNumber)));
374 if (funcName != nullptr)
377 formatString("(call to %s() returned error code %d)",
378 funcName, errorNumber));
387 * Exception information writer to format into an std::string.
389 class MessageWriterString : public IMessageWriter
392 //! Post-processes the output string to not end in a line feed.
393 void removeTerminatingLineFeed()
395 if (result_.size() > 0U)
397 result_.erase(result_.size() - 1);
400 //! Returns the constructed string.
401 const std::string &result() const { return result_; }
403 virtual void writeLine(const char *text, int indent)
405 result_.append(indent, ' ');
406 result_.append(text);
407 result_.append("\n");
409 virtual void writeErrNoInfo(int errorNumber, const char *funcName,
412 writeLine(formatString("Reason: %s", std::strerror(errorNumber)).c_str(),
414 if (funcName != nullptr)
416 writeLine(formatString("(call to %s() returned error code %d)",
417 funcName, errorNumber).c_str(),
427 * Prints error information for an exception object.
429 * \param[in] writer Writer to write out the information.
430 * \param[in] ex Exception object to print.
431 * \param[in] indent Indentation for the information.
433 * If the exception contains nested exceptions, information from them is
434 * recursively printed.
436 * Does not throw unless the writer throws.
438 void formatExceptionMessageInternal(IMessageWriter *writer,
439 const std::exception &ex, int indent)
441 const GromacsException *gmxEx = dynamic_cast<const GromacsException *>(&ex);
442 if (gmxEx != nullptr)
444 // TODO: Add an option to print location information for the tests
446 // std::string result;
447 // if (filePtr != NULL && linePtr != NULL)
449 // result = formatString("%s:%d: %s\n", *filePtr, *linePtr,
450 // funcPtr != NULL ? *funcPtr : "");
453 bool bAnythingWritten = false;
454 // TODO: Remove duplicate context if present in multiple nested exceptions.
455 const ErrorMessage *msg = gmxEx->getInfo<ExceptionInfoMessage>();
458 while (msg != nullptr && msg->isContext())
460 writer->writeLine(msg->text().c_str(), indent*2);
464 if (msg != nullptr && !msg->text().empty())
466 writer->writeLine(msg->text().c_str(), indent*2);
467 bAnythingWritten = true;
472 writer->writeLine(ex.what(), indent*2);
473 bAnythingWritten = true;
476 const int *errorNumber = gmxEx->getInfo<ExceptionInfoErrno>();
477 if (errorNumber != nullptr && *errorNumber != 0)
479 const char * const *funcName
480 = gmxEx->getInfo<ExceptionInfoApiFunction>();
481 writer->writeErrNoInfo(*errorNumber,
482 funcName != nullptr ? *funcName : nullptr,
484 bAnythingWritten = true;
487 const internal::NestedExceptionList *nested
488 = gmxEx->getInfo<ExceptionInfoNestedExceptions>();
489 if (nested != nullptr)
491 internal::NestedExceptionList::const_iterator ni;
492 for (ni = nested->begin(); ni != nested->end(); ++ni)
496 std::rethrow_exception(*ni);
498 catch (const std::exception &nestedEx)
500 const int newIndent = indent + (bAnythingWritten ? 1 : 0);
501 formatExceptionMessageInternal(writer, nestedEx, newIndent);
508 writer->writeLine(ex.what(), indent*2);
516 void printFatalErrorMessage(FILE *fp, const std::exception &ex)
518 const char *title = "Unknown exception";
519 bool bPrintType = false;
520 const GromacsException *gmxEx = dynamic_cast<const GromacsException *>(&ex);
521 // TODO: Treat more of the standard exceptions
522 if (gmxEx != nullptr)
524 title = getErrorCodeString(gmxEx->errorCode());
526 else if (dynamic_cast<const tMPI::system_error *>(&ex) != nullptr)
528 title = "System error in thread synchronization";
530 else if (dynamic_cast<const std::bad_alloc *>(&ex) != nullptr)
532 title = "Memory allocation failed";
534 else if (dynamic_cast<const std::logic_error *>(&ex) != nullptr)
536 title = "Standard library logic error (bug)";
539 else if (dynamic_cast<const std::runtime_error *>(&ex) != nullptr)
541 title = "Standard library runtime error (possible bug)";
548 const char *func = nullptr;
549 const char *file = nullptr;
551 if (gmxEx != nullptr)
553 const ThrowLocation *loc = gmxEx->getInfo<ExceptionInfoLocation>();
561 internal::printFatalErrorHeader(fp, title, func, file, line);
564 std::fprintf(fp, "(exception type: %s)\n", typeid(ex).name());
566 MessageWriterFileNoThrow writer(fp);
567 formatExceptionMessageInternal(&writer, ex, 0);
568 internal::printFatalErrorFooter(fp);
571 std::string formatExceptionMessageToString(const std::exception &ex)
573 MessageWriterString writer;
574 formatExceptionMessageInternal(&writer, ex, 0);
575 writer.removeTerminatingLineFeed();
576 return writer.result();
579 void formatExceptionMessageToFile(FILE *fp, const std::exception &ex)
581 MessageWriterFileNoThrow writer(fp);
582 formatExceptionMessageInternal(&writer, ex, 0);
585 void formatExceptionMessageToWriter(TextWriter *writer,
586 const std::exception &ex)
588 MessageWriterTextWriter messageWriter(writer);
589 formatExceptionMessageInternal(&messageWriter, ex, 0);
592 int processExceptionAtExit(const std::exception & /*ex*/)
595 // If we have more than one rank (whether real MPI or thread-MPI),
596 // we cannot currently know whether just one rank or all ranks
597 // actually threw the error, so we need to exit here.
598 // Returning would mean graceful cleanup, which is not possible if
599 // some code is still executing on other ranks/threads.
600 if (gmx_node_num() > 1)
602 gmx_exit_on_fatal_error(ExitType_Abort, returnCode);
607 void processExceptionAsFatalError(const std::exception &ex)
609 printFatalErrorMessage(stderr, ex);
610 gmx_exit_on_fatal_error(ExitType_Abort, 1);