2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2011,2012,2013,2014, 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
42 #include "exceptions.h"
54 #include <boost/exception/get_error_info.hpp>
55 #include <boost/shared_ptr.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"
64 #include "errorformat.h"
72 /********************************************************************
77 * Error message or error context text item.
79 * Error messages for an exception are represented as a chain of ErrorMessage
80 * objects: the elements at the bottom of the chain (with no children) is the
81 * error message, and other elements are the context strings added.
83 * \ingroup module_utility
89 * Creates an error message object with the specified text.
91 * \param[in] text Text for the message.
93 explicit ErrorMessage(const std::string &text);
95 //! Whether this object is a context string.
96 bool isContext() const { return static_cast<bool>(child_); }
97 //! Returns the text for this object.
98 const std::string &text() const { return text_; }
100 * Returns the child object for a context object.
102 * Must not be called if isContext() returns false.
104 const ErrorMessage &child() const
106 GMX_ASSERT(isContext(),
107 "Attempting to access nonexistent message object");
112 * Creates a new message object with context prepended.
114 * \param[in] context Context string to add.
115 * \returns New error message object that has \p context as its text
116 * and \c this as its child.
117 * \throws std::bad_alloc if out of memory.
119 ErrorMessage prependContext(const std::string &context) const;
123 boost::shared_ptr<ErrorMessage> child_;
127 * Stores a reason or the top-most context string of an exception.
129 * \ingroup module_utility
131 typedef boost::error_info<struct errinfo_message_, ErrorMessage>
134 ErrorMessage::ErrorMessage(const std::string &text)
137 size_t length = text_.find_last_not_of(" \n");
138 if (length == std::string::npos)
140 length = text_.length() - 1;
142 text_.resize(length + 1);
146 ErrorMessage::prependContext(const std::string &context) const
148 ErrorMessage newMessage(context);
149 newMessage.child_.reset(new ErrorMessage(*this));
154 * Stores list of nested exceptions for Gromacs exceptions.
156 * \ingroup module_utility
158 typedef boost::error_info<struct errinfo_message_, internal::NestedExceptionList>
159 errinfo_nested_exceptions;
163 /********************************************************************
167 GromacsException::GromacsException(const ExceptionInitializer &details)
169 *this << errinfo_message(ErrorMessage(details.reason_));
170 if (details.hasNestedExceptions())
172 *this << errinfo_nested_exceptions(details.nested_);
176 const char *GromacsException::what() const throw()
178 const ErrorMessage *msg = boost::get_error_info<errinfo_message>(*this);
179 while (msg != NULL && msg->isContext())
183 return msg != NULL ? msg->text().c_str() : "No reason provided";
186 void GromacsException::prependContext(const std::string &context)
188 const ErrorMessage *msg = boost::get_error_info<errinfo_message>(*this);
189 GMX_RELEASE_ASSERT(msg != NULL, "Message should always be set");
190 *this << errinfo_message(msg->prependContext(context));
193 /********************************************************************
194 * Derived exception classes
197 int FileIOError::errorCode() const
202 int InvalidInputError::errorCode() const
204 return eeInvalidInput;
207 int InconsistentInputError::errorCode() const
209 return eeInconsistentInput;
212 int SimulationInstabilityError::errorCode() const
214 return eeInstability;
217 int InternalError::errorCode() const
219 return eeInternalError;
222 int APIError::errorCode() const
227 int NotImplementedError::errorCode() const
229 return eeNotImplemented;
233 /********************************************************************
240 //! \addtogroup module_utility
244 * Abstracts actual output from the other logic in exception formatting.
246 * Object that implements this interface is passed to
247 * formatExceptionMessageInternal(), and is responsible for composing the
248 * output. This allows using the same implementation of interpreting the
249 * exceptions while still supporting output to different formats (e.g., to a
250 * string or to \c stderr).
252 class MessageWriterInterface
255 virtual ~MessageWriterInterface() {}
258 * Writes a single line of text into the output.
260 * \param[in] text Text to write on the line.
261 * \param[in] indent Suggested number of spaces to indent the line.
263 virtual void writeLine(const char *text, int indent) = 0;
265 * Writes information about a system error (errno-based).
267 * \param[in] errorNumber errno value
268 * \param[in] funcName Name of the system call (can be NULL).
269 * \param[in] indent Suggested number of spaces to indent the output.
271 virtual void writeErrNoInfo(int errorNumber, const char *funcName,
276 * Exception information writer for cases where exceptions should be avoided.
278 * Formats the messages into the provided FILE handle without checking for
279 * errors in std::fprintf() calls.
281 class MessageWriterFileNoThrow : public MessageWriterInterface
284 //! Initializes a writer that writes to the given file handle.
285 explicit MessageWriterFileNoThrow(FILE *fp) : fp_(fp) {}
287 virtual void writeLine(const char *text, int indent)
289 internal::printFatalErrorMessageLine(fp_, text, indent);
291 virtual void writeErrNoInfo(int errorNumber, const char *funcName,
294 std::fprintf(fp_, "%*sReason: %s\n", indent, "",
295 std::strerror(errorNumber));
296 if (funcName != NULL)
298 std::fprintf(fp_, "%*s(call to %s() returned error code %d)\n",
299 indent, "", funcName, errorNumber);
308 * Exception information writer to format into an std::string.
310 class MessageWriterString : public MessageWriterInterface
313 //! Post-processes the output string to not end in a line feed.
314 void removeTerminatingLineFeed()
316 if (result_.size() > 0U)
318 result_.erase(result_.size() - 1);
321 //! Returns the constructed string.
322 const std::string &result() const { return result_; }
324 virtual void writeLine(const char *text, int indent)
326 result_.append(indent, ' ');
327 result_.append(text);
328 result_.append("\n");
330 virtual void writeErrNoInfo(int errorNumber, const char *funcName,
333 writeLine(formatString("Reason: %s", std::strerror(errorNumber)).c_str(),
335 if (funcName != NULL)
337 writeLine(formatString("(call to %s() returned error code %d)",
338 funcName, errorNumber).c_str(),
348 * Prints error information for an exception object.
350 * \param[in] writer Writer to write out the information.
351 * \param[in] ex Exception object to print.
352 * \param[in] indent Indentation for the information.
354 * If the exception contains nested exceptions, information from them is
355 * recursively printed.
357 * Does not throw unless the writer throws.
359 void formatExceptionMessageInternal(MessageWriterInterface *writer,
360 const std::exception &ex, int indent)
362 const boost::exception *boostEx = dynamic_cast<const boost::exception *>(&ex);
365 // TODO: Add an option to print this information for the tests
366 // const char *const *funcPtr =
367 // boost::get_error_info<boost::throw_function>(*boostEx);
368 // const char *const *filePtr =
369 // boost::get_error_info<boost::throw_file>(*boostEx);
370 // const int *linePtr =
371 // boost::get_error_info<boost::throw_line>(*boostEx);
373 // std::string result;
374 // if (filePtr != NULL && linePtr != NULL)
376 // result = formatString("%s:%d: %s\n", *filePtr, *linePtr,
377 // funcPtr != NULL ? *funcPtr : "");
380 // TODO: Remove duplicate context if present in multiple nested exceptions.
381 const ErrorMessage *msg = boost::get_error_info<errinfo_message>(*boostEx);
384 while (msg != NULL && msg->isContext())
386 writer->writeLine(msg->text().c_str(), indent*2);
390 if (msg != NULL && !msg->text().empty())
392 writer->writeLine(msg->text().c_str(), indent*2);
397 writer->writeLine(ex.what(), indent*2);
400 const int *errorNumber
401 = boost::get_error_info<boost::errinfo_errno>(*boostEx);
402 if (errorNumber != NULL)
404 const char * const *funcName
405 = boost::get_error_info<boost::errinfo_api_function>(*boostEx);
406 writer->writeErrNoInfo(*errorNumber,
407 funcName != NULL ? *funcName : NULL,
411 // TODO: Treat also boost::nested_exception (not currently used, though)
413 const internal::NestedExceptionList *nested
414 = boost::get_error_info<errinfo_nested_exceptions>(*boostEx);
417 internal::NestedExceptionList::const_iterator ni;
418 for (ni = nested->begin(); ni != nested->end(); ++ni)
422 rethrow_exception(*ni);
424 catch (const std::exception &nestedEx)
426 formatExceptionMessageInternal(writer, nestedEx, indent + 1);
433 writer->writeLine(ex.what(), indent*2);
441 void printFatalErrorMessage(FILE *fp, const std::exception &ex)
443 const char *title = "Unknown exception";
444 bool bPrintType = false;
445 const GromacsException *gmxEx = dynamic_cast<const GromacsException *>(&ex);
446 // TODO: Treat more of the standard exceptions
449 title = getErrorCodeString(gmxEx->errorCode());
451 else if (dynamic_cast<const tMPI::system_error *>(&ex) != NULL)
453 title = "System error in thread synchronization";
455 else if (dynamic_cast<const std::bad_alloc *>(&ex) != NULL)
457 title = "Memory allocation failed";
459 else if (dynamic_cast<const std::logic_error *>(&ex) != NULL)
461 title = "Standard library logic error (bug)";
464 else if (dynamic_cast<const std::runtime_error *>(&ex) != NULL)
466 title = "Standard library runtime error (possible bug)";
473 // We can't call get_error_info directly on ex since our internal boost
474 // needs to be compiled with BOOST_NO_RTTI. So we do the dynamic_cast
476 const char *const *funcPtr = NULL;
477 const char *const *filePtr = NULL;
478 const int *linePtr = NULL;
479 const boost::exception *boostEx = dynamic_cast<const boost::exception *>(&ex);
482 funcPtr = boost::get_error_info<boost::throw_function>(*boostEx);
483 filePtr = boost::get_error_info<boost::throw_file>(*boostEx);
484 linePtr = boost::get_error_info<boost::throw_line>(*boostEx);
486 internal::printFatalErrorHeader(fp, title,
487 funcPtr != NULL ? *funcPtr : NULL,
488 filePtr != NULL ? *filePtr : NULL,
489 linePtr != NULL ? *linePtr : 0);
492 std::fprintf(fp, "(exception type: %s)\n", typeid(ex).name());
494 MessageWriterFileNoThrow writer(fp);
495 formatExceptionMessageInternal(&writer, ex, 0);
496 internal::printFatalErrorFooter(fp);
499 std::string formatExceptionMessageToString(const std::exception &ex)
501 MessageWriterString writer;
502 formatExceptionMessageInternal(&writer, ex, 0);
503 writer.removeTerminatingLineFeed();
504 return writer.result();
507 void formatExceptionMessageToFile(FILE *fp, const std::exception &ex)
509 MessageWriterFileNoThrow writer(fp);
510 formatExceptionMessageInternal(&writer, ex, 0);
513 int processExceptionAtExit(const std::exception & /*ex*/)
517 // TODO: Consider moving the output done in gmx_abort() into the message
518 // printing routine above, so that this could become a simple MPI_Abort().
519 gmx_abort(returnCode);