2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2011,2012,2013,2014,2015, 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 <boost/shared_ptr.hpp>
55 #include <boost/exception/get_error_info.hpp>
57 #include "thread_mpi/system_error.h"
59 #include "gromacs/utility/basenetwork.h"
60 #include "gromacs/utility/errorcodes.h"
61 #include "gromacs/utility/gmxassert.h"
62 #include "gromacs/utility/stringutil.h"
63 #include "gromacs/utility/textwriter.h"
65 #include "errorformat.h"
73 /********************************************************************
78 * Error message or error context text item.
80 * Error messages for an exception are represented as a chain of ErrorMessage
81 * objects: the elements at the bottom of the chain (with no children) is the
82 * error message, and other elements are the context strings added.
84 * \ingroup module_utility
90 * Creates an error message object with the specified text.
92 * \param[in] text Text for the message.
94 explicit ErrorMessage(const std::string &text);
96 //! Whether this object is a context string.
97 bool isContext() const { return static_cast<bool>(child_); }
98 //! Returns the text for this object.
99 const std::string &text() const { return text_; }
101 * Returns the child object for a context object.
103 * Must not be called if isContext() returns false.
105 const ErrorMessage &child() const
107 GMX_ASSERT(isContext(),
108 "Attempting to access nonexistent message object");
113 * Creates a new message object with context prepended.
115 * \param[in] context Context string to add.
116 * \returns New error message object that has \p context as its text
117 * and \c this as its child.
118 * \throws std::bad_alloc if out of memory.
120 ErrorMessage prependContext(const std::string &context) const;
124 boost::shared_ptr<ErrorMessage> child_;
128 * Stores a reason or the top-most context string of an exception.
130 * \ingroup module_utility
132 typedef boost::error_info<struct errinfo_message_, ErrorMessage>
135 ErrorMessage::ErrorMessage(const std::string &text)
138 size_t length = text_.find_last_not_of(" \n");
139 if (length == std::string::npos)
141 length = text_.length() - 1;
143 text_.resize(length + 1);
147 ErrorMessage::prependContext(const std::string &context) const
149 ErrorMessage newMessage(context);
150 newMessage.child_.reset(new ErrorMessage(*this));
155 * Stores list of nested exceptions for Gromacs exceptions.
157 * \ingroup module_utility
159 typedef boost::error_info<struct errinfo_message_, internal::NestedExceptionList>
160 errinfo_nested_exceptions;
164 /********************************************************************
168 GromacsException::GromacsException(const ExceptionInitializer &details)
170 *this << errinfo_message(ErrorMessage(details.reason_));
171 if (details.hasNestedExceptions())
173 *this << errinfo_nested_exceptions(details.nested_);
177 const char *GromacsException::what() const throw()
179 const ErrorMessage *msg = boost::get_error_info<errinfo_message>(*this);
182 return "No reason provided";
184 while (msg->isContext())
188 return msg->text().c_str();
191 void GromacsException::prependContext(const std::string &context)
193 const ErrorMessage *msg = boost::get_error_info<errinfo_message>(*this);
194 GMX_RELEASE_ASSERT(msg != NULL, "Message should always be set");
195 *this << errinfo_message(msg->prependContext(context));
198 /********************************************************************
199 * Derived exception classes
202 int FileIOError::errorCode() const
207 int InvalidInputError::errorCode() const
209 return eeInvalidInput;
212 int InconsistentInputError::errorCode() const
214 return eeInconsistentInput;
217 int SimulationInstabilityError::errorCode() const
219 return eeInstability;
222 int InternalError::errorCode() const
224 return eeInternalError;
227 int APIError::errorCode() const
232 int NotImplementedError::errorCode() const
234 return eeNotImplemented;
238 /********************************************************************
245 //! \addtogroup module_utility
249 * Abstracts actual output from the other logic in exception formatting.
251 * Object that implements this interface is passed to
252 * formatExceptionMessageInternal(), and is responsible for composing the
253 * output. This allows using the same implementation of interpreting the
254 * exceptions while still supporting output to different formats (e.g., to a
255 * string or to \c stderr).
260 virtual ~IMessageWriter() {}
263 * Writes a single line of text into the output.
265 * \param[in] text Text to write on the line.
266 * \param[in] indent Suggested number of spaces to indent the line.
268 virtual void writeLine(const char *text, int indent) = 0;
270 * Writes information about a system error (errno-based).
272 * \param[in] errorNumber errno value
273 * \param[in] funcName Name of the system call (can be NULL).
274 * \param[in] indent Suggested number of spaces to indent the output.
276 virtual void writeErrNoInfo(int errorNumber, const char *funcName,
281 * Exception information writer for cases where exceptions should be avoided.
283 * Formats the messages into the provided FILE handle without checking for
284 * errors in std::fprintf() calls.
286 class MessageWriterFileNoThrow : public IMessageWriter
289 //! Initializes a writer that writes to the given file handle.
290 explicit MessageWriterFileNoThrow(FILE *fp) : fp_(fp) {}
292 virtual void writeLine(const char *text, int indent)
294 internal::printFatalErrorMessageLine(fp_, text, indent);
296 virtual void writeErrNoInfo(int errorNumber, const char *funcName,
299 std::fprintf(fp_, "%*sReason: %s\n", indent, "",
300 std::strerror(errorNumber));
301 if (funcName != NULL)
303 std::fprintf(fp_, "%*s(call to %s() returned error code %d)\n",
304 indent, "", funcName, errorNumber);
313 * Exception information writer to format into a TextOutputStream.
315 class MessageWriterTextWriter : public IMessageWriter
318 //! Initializes a writer that writes to the given stream.
319 explicit MessageWriterTextWriter(TextWriter *writer) : writer_(writer)
323 virtual void writeLine(const char *text, int indent)
325 writer_->wrapperSettings().setIndent(indent);
326 writer_->writeLine(text);
328 virtual void writeErrNoInfo(int errorNumber, const char *funcName,
331 writer_->wrapperSettings().setIndent(indent);
332 writer_->writeLine(formatString("Reason: %s", std::strerror(errorNumber)));
333 if (funcName != NULL)
336 formatString("(call to %s() returned error code %d)",
337 funcName, errorNumber));
346 * Exception information writer to format into an std::string.
348 class MessageWriterString : public IMessageWriter
351 //! Post-processes the output string to not end in a line feed.
352 void removeTerminatingLineFeed()
354 if (result_.size() > 0U)
356 result_.erase(result_.size() - 1);
359 //! Returns the constructed string.
360 const std::string &result() const { return result_; }
362 virtual void writeLine(const char *text, int indent)
364 result_.append(indent, ' ');
365 result_.append(text);
366 result_.append("\n");
368 virtual void writeErrNoInfo(int errorNumber, const char *funcName,
371 writeLine(formatString("Reason: %s", std::strerror(errorNumber)).c_str(),
373 if (funcName != NULL)
375 writeLine(formatString("(call to %s() returned error code %d)",
376 funcName, errorNumber).c_str(),
386 * Prints error information for an exception object.
388 * \param[in] writer Writer to write out the information.
389 * \param[in] ex Exception object to print.
390 * \param[in] indent Indentation for the information.
392 * If the exception contains nested exceptions, information from them is
393 * recursively printed.
395 * Does not throw unless the writer throws.
397 void formatExceptionMessageInternal(IMessageWriter *writer,
398 const std::exception &ex, int indent)
400 const boost::exception *boostEx = dynamic_cast<const boost::exception *>(&ex);
403 // TODO: Add an option to print this information for the tests
404 // const char *const *funcPtr =
405 // boost::get_error_info<boost::throw_function>(*boostEx);
406 // const char *const *filePtr =
407 // boost::get_error_info<boost::throw_file>(*boostEx);
408 // const int *linePtr =
409 // boost::get_error_info<boost::throw_line>(*boostEx);
411 // std::string result;
412 // if (filePtr != NULL && linePtr != NULL)
414 // result = formatString("%s:%d: %s\n", *filePtr, *linePtr,
415 // funcPtr != NULL ? *funcPtr : "");
418 bool bAnythingWritten = false;
419 // TODO: Remove duplicate context if present in multiple nested exceptions.
420 const ErrorMessage *msg = boost::get_error_info<errinfo_message>(*boostEx);
423 while (msg != NULL && msg->isContext())
425 writer->writeLine(msg->text().c_str(), indent*2);
429 if (msg != NULL && !msg->text().empty())
431 writer->writeLine(msg->text().c_str(), indent*2);
432 bAnythingWritten = true;
437 writer->writeLine(ex.what(), indent*2);
438 bAnythingWritten = true;
441 const int *errorNumber
442 = boost::get_error_info<boost::errinfo_errno>(*boostEx);
443 if (errorNumber != NULL)
445 const char * const *funcName
446 = boost::get_error_info<boost::errinfo_api_function>(*boostEx);
447 writer->writeErrNoInfo(*errorNumber,
448 funcName != NULL ? *funcName : NULL,
450 bAnythingWritten = true;
453 // TODO: Treat also boost::nested_exception (not currently used, though)
455 const internal::NestedExceptionList *nested
456 = boost::get_error_info<errinfo_nested_exceptions>(*boostEx);
459 internal::NestedExceptionList::const_iterator ni;
460 for (ni = nested->begin(); ni != nested->end(); ++ni)
464 rethrow_exception(*ni);
466 catch (const std::exception &nestedEx)
468 const int newIndent = indent + (bAnythingWritten ? 1 : 0);
469 formatExceptionMessageInternal(writer, nestedEx, newIndent);
476 writer->writeLine(ex.what(), indent*2);
484 void printFatalErrorMessage(FILE *fp, const std::exception &ex)
486 const char *title = "Unknown exception";
487 bool bPrintType = false;
488 const GromacsException *gmxEx = dynamic_cast<const GromacsException *>(&ex);
489 // TODO: Treat more of the standard exceptions
492 title = getErrorCodeString(gmxEx->errorCode());
494 else if (dynamic_cast<const tMPI::system_error *>(&ex) != NULL)
496 title = "System error in thread synchronization";
498 else if (dynamic_cast<const std::bad_alloc *>(&ex) != NULL)
500 title = "Memory allocation failed";
502 else if (dynamic_cast<const std::logic_error *>(&ex) != NULL)
504 title = "Standard library logic error (bug)";
507 else if (dynamic_cast<const std::runtime_error *>(&ex) != NULL)
509 title = "Standard library runtime error (possible bug)";
516 // We can't call get_error_info directly on ex since our internal boost
517 // needs to be compiled with BOOST_NO_RTTI. So we do the dynamic_cast
519 const char *const *funcPtr = NULL;
520 const char *const *filePtr = NULL;
521 const int *linePtr = NULL;
522 const boost::exception *boostEx = dynamic_cast<const boost::exception *>(&ex);
525 funcPtr = boost::get_error_info<boost::throw_function>(*boostEx);
526 filePtr = boost::get_error_info<boost::throw_file>(*boostEx);
527 linePtr = boost::get_error_info<boost::throw_line>(*boostEx);
529 internal::printFatalErrorHeader(fp, title,
530 funcPtr != NULL ? *funcPtr : NULL,
531 filePtr != NULL ? *filePtr : NULL,
532 linePtr != NULL ? *linePtr : 0);
535 std::fprintf(fp, "(exception type: %s)\n", typeid(ex).name());
537 MessageWriterFileNoThrow writer(fp);
538 formatExceptionMessageInternal(&writer, ex, 0);
539 internal::printFatalErrorFooter(fp);
542 std::string formatExceptionMessageToString(const std::exception &ex)
544 MessageWriterString writer;
545 formatExceptionMessageInternal(&writer, ex, 0);
546 writer.removeTerminatingLineFeed();
547 return writer.result();
550 void formatExceptionMessageToFile(FILE *fp, const std::exception &ex)
552 MessageWriterFileNoThrow writer(fp);
553 formatExceptionMessageInternal(&writer, ex, 0);
556 void formatExceptionMessageToWriter(TextWriter *writer,
557 const std::exception &ex)
559 MessageWriterTextWriter messageWriter(writer);
560 formatExceptionMessageInternal(&messageWriter, ex, 0);
563 int processExceptionAtExit(const std::exception & /*ex*/)
567 // TODO: Consider moving the output done in gmx_abort() into the message
568 // printing routine above, so that this could become a simple MPI_Abort().
569 gmx_abort(returnCode);