2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2011,2012,2013, by the GROMACS development team, led by
5 * David van der Spoel, Berk Hess, Erik Lindahl, and including many
6 * others, as listed in the AUTHORS file in the top-level source
7 * 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 "gromacs/legacyheaders/network.h"
58 #include "gromacs/legacyheaders/thread_mpi/system_error.h"
59 #include "gromacs/utility/errorcodes.h"
60 #include "gromacs/utility/gmxassert.h"
61 #include "gromacs/utility/stringutil.h"
63 #include "errorformat.h"
71 /********************************************************************
79 * Creates an error message object with the specified text.
81 * \param[in] text Text for the message.
83 explicit ErrorMessage(const std::string &text);
85 //! Whether this object is a context string.
86 bool isContext() const { return static_cast<bool>(child_); }
87 //! Returns the text for this object.
88 const std::string &text() const { return text_; }
90 * Returns the child object for a context object.
92 * Must not be called if isContext() returns false.
94 const ErrorMessage &child() const
96 GMX_ASSERT(isContext(),
97 "Attempting to access nonexistent message object");
102 * Creates a new message object with context prepended.
104 * \param[in] context Context string to add.
105 * \returns New error message object that has \p context as its text
106 * and \c this as its child.
107 * \throws std::bad_alloc if out of memory.
109 ErrorMessage prependContext(const std::string &context) const;
113 boost::shared_ptr<ErrorMessage> child_;
117 * Stores a reason or the top-most context string of an exception.
119 * \ingroup module_utility
121 typedef boost::error_info<struct errinfo_message_, ErrorMessage>
124 ErrorMessage::ErrorMessage(const std::string &text)
127 size_t length = text_.find_last_not_of(" \n");
128 if (length == std::string::npos)
130 length = text_.length() - 1;
132 text_.resize(length + 1);
136 ErrorMessage::prependContext(const std::string &context) const
138 ErrorMessage newMessage(context);
139 newMessage.child_.reset(new ErrorMessage(*this));
144 * Stores list of nested exceptions for Gromacs exceptions.
146 * \ingroup module_utility
148 typedef boost::error_info<struct errinfo_message_, internal::NestedExceptionList>
149 errinfo_nested_exceptions;
153 /********************************************************************
157 GromacsException::GromacsException(const ExceptionInitializer &details)
159 *this << errinfo_message(ErrorMessage(details.reason_));
160 if (details.hasNestedExceptions())
162 *this << errinfo_nested_exceptions(details.nested_);
166 const char *GromacsException::what() const throw()
168 const ErrorMessage *msg = boost::get_error_info<errinfo_message>(*this);
169 while (msg != NULL && msg->isContext())
173 return msg != NULL ? msg->text().c_str() : "No reason provided";
176 void GromacsException::prependContext(const std::string &context)
178 const ErrorMessage *msg = boost::get_error_info<errinfo_message>(*this);
179 GMX_RELEASE_ASSERT(msg != NULL, "Message should always be set");
180 *this << errinfo_message(msg->prependContext(context));
183 /********************************************************************
184 * Derived exception classes
187 int FileIOError::errorCode() const
192 int InvalidInputError::errorCode() const
194 return eeInvalidInput;
197 int InconsistentInputError::errorCode() const
199 return eeInconsistentInput;
202 int SimulationInstabilityError::errorCode() const
204 return eeInstability;
207 int InternalError::errorCode() const
209 return eeInternalError;
212 int APIError::errorCode() const
217 int NotImplementedError::errorCode() const
219 return eeNotImplemented;
223 /********************************************************************
231 * Abstracts actual output from the other logic in exception formatting.
233 * Object that implements this interface is passed to
234 * formatExceptionMessageInternal(), and is responsible for composing the
235 * output. This allows using the same implementation of interpreting the
236 * exceptions while still supporting output to different formats (e.g., to a
237 * string or to stderr).
239 class MessageWriterInterface
242 virtual ~MessageWriterInterface() {}
245 * Writes a single line of text into the output.
247 * \param[in] text Text to write on the line.
248 * \param[in] indent Suggested number of spaces to indent the line.
250 virtual void writeLine(const char *text, int indent) = 0;
252 * Writes information about a system error (errno-based).
254 * \param[in] errorNumber errno value
255 * \param[in] funcName Name of the system call (can be NULL).
256 * \param[in] indent Suggested number of spaces to indent the output.
258 virtual void writeErrNoInfo(int errorNumber, const char *funcName,
263 * Exception information writer for cases where exceptions should be avoided.
265 * Formats the messages into the provided FILE handle without checking for
266 * errors in fprintf() calls.
268 class MessageWriterFileNoThrow : public MessageWriterInterface
271 //! Initializes a writer that writes to the given file handle.
272 explicit MessageWriterFileNoThrow(FILE *fp) : fp_(fp) {}
274 virtual void writeLine(const char *text, int indent)
276 internal::printFatalErrorMessageLine(fp_, text, indent);
278 virtual void writeErrNoInfo(int errorNumber, const char *funcName,
281 std::fprintf(fp_, "%*sReason: %s\n", indent, "",
282 std::strerror(errorNumber));
283 if (funcName != NULL)
285 std::fprintf(fp_, "%*s(call to %s() returned error code %d)\n",
286 indent, "", funcName, errorNumber);
295 * Exception information writer to format into an std::string.
297 class MessageWriterString : public MessageWriterInterface
300 //! Post-processes the output string to not end in a line feed.
301 void removeTerminatingLineFeed()
303 if (result_.size() > 0U)
305 result_.erase(result_.size() - 1);
308 //! Returns the constructed string.
309 const std::string &result() const { return result_; }
311 virtual void writeLine(const char *text, int indent)
313 result_.append(indent, ' ');
314 result_.append(text);
315 result_.append("\n");
317 virtual void writeErrNoInfo(int errorNumber, const char *funcName,
320 writeLine(formatString("Reason: %s", std::strerror(errorNumber)).c_str(),
322 if (funcName != NULL)
324 writeLine(formatString("(call to %s() returned error code %d)",
325 funcName, errorNumber).c_str(),
335 * Prints error information for an exception object.
337 * \param[in] writer Writer to write out the information.
338 * \param[in] ex Exception object to print.
339 * \param[in] indent Indentation for the information.
341 * If the exception contains nested exceptions, information from them is
342 * recursively printed.
344 * Does not throw unless the writer throws.
346 void formatExceptionMessageInternal(MessageWriterInterface *writer,
347 const std::exception &ex, int indent)
349 const boost::exception *boostEx = dynamic_cast<const boost::exception *>(&ex);
352 // TODO: Add an option to print this information for the tests
353 // const char *const *funcPtr =
354 // boost::get_error_info<boost::throw_function>(*boostEx);
355 // const char *const *filePtr =
356 // boost::get_error_info<boost::throw_file>(*boostEx);
357 // const int *linePtr =
358 // boost::get_error_info<boost::throw_line>(*boostEx);
360 // std::string result;
361 // if (filePtr != NULL && linePtr != NULL)
363 // result = formatString("%s:%d: %s\n", *filePtr, *linePtr,
364 // funcPtr != NULL ? *funcPtr : "");
367 // TODO: Remove duplicate context if present in multiple nested exceptions.
368 const ErrorMessage *msg = boost::get_error_info<errinfo_message>(*boostEx);
371 while (msg != NULL && msg->isContext())
373 writer->writeLine(msg->text().c_str(), indent*2);
377 if (msg != NULL && !msg->text().empty())
379 writer->writeLine(msg->text().c_str(), indent*2);
384 writer->writeLine(ex.what(), indent*2);
387 const int *errorNumber
388 = boost::get_error_info<boost::errinfo_errno>(*boostEx);
389 if (errorNumber != NULL)
391 const char * const *funcName
392 = boost::get_error_info<boost::errinfo_api_function>(*boostEx);
393 writer->writeErrNoInfo(*errorNumber,
394 funcName != NULL ? *funcName : NULL,
398 // TODO: Treat also boost::nested_exception (not currently used, though)
400 const internal::NestedExceptionList *nested
401 = boost::get_error_info<errinfo_nested_exceptions>(*boostEx);
404 internal::NestedExceptionList::const_iterator ni;
405 for (ni = nested->begin(); ni != nested->end(); ++ni)
409 rethrow_exception(*ni);
411 catch (const std::exception &nestedEx)
413 formatExceptionMessageInternal(writer, nestedEx, indent + 1);
420 writer->writeLine(ex.what(), indent*2);
426 void printFatalErrorMessage(FILE *fp, const std::exception &ex)
428 const char *title = "Unknown exception";
429 bool bPrintType = false;
430 const GromacsException *gmxEx = dynamic_cast<const GromacsException *>(&ex);
431 // TODO: Treat more of the standard exceptions
434 title = getErrorCodeString(gmxEx->errorCode());
436 else if (dynamic_cast<const tMPI::system_error *>(&ex) != NULL)
438 title = "System error in thread synchronization";
440 else if (dynamic_cast<const std::bad_alloc *>(&ex) != NULL)
442 title = "Memory allocation failed";
444 else if (dynamic_cast<const std::logic_error *>(&ex) != NULL)
446 title = "Standard library logic error (bug)";
449 else if (dynamic_cast<const std::runtime_error *>(&ex) != NULL)
451 title = "Standard library runtime error (possible bug)";
458 // We can't call get_error_info directly on ex since our internal boost
459 // needs to be compiled with BOOST_NO_RTTI. So we do the dynamic_cast
461 const char *const *funcPtr = NULL;
462 const char *const *filePtr = NULL;
463 const int *linePtr = NULL;
464 const boost::exception *boostEx = dynamic_cast<const boost::exception *>(&ex);
467 funcPtr = boost::get_error_info<boost::throw_function>(*boostEx);
468 filePtr = boost::get_error_info<boost::throw_file>(*boostEx);
469 linePtr = boost::get_error_info<boost::throw_line>(*boostEx);
471 internal::printFatalErrorHeader(fp, title,
472 funcPtr != NULL ? *funcPtr : NULL,
473 filePtr != NULL ? *filePtr : NULL,
474 linePtr != NULL ? *linePtr : 0);
477 std::fprintf(fp, "(exception type: %s)\n", typeid(ex).name());
479 MessageWriterFileNoThrow writer(fp);
480 formatExceptionMessageInternal(&writer, ex, 0);
481 internal::printFatalErrorFooter(fp);
484 std::string formatExceptionMessageToString(const std::exception &ex)
486 MessageWriterString writer;
487 formatExceptionMessageInternal(&writer, ex, 0);
488 writer.removeTerminatingLineFeed();
489 return writer.result();
492 void formatExceptionMessageToFile(FILE *fp, const std::exception &ex)
494 MessageWriterFileNoThrow writer(fp);
495 formatExceptionMessageInternal(&writer, ex, 0);
498 int processExceptionAtExit(const std::exception &/*ex*/)
502 // TODO: Consider moving the output done in gmx_abort() into the message
503 // printing routine above, so that this could become a simple MPI_Abort().
504 gmx_abort(gmx_node_rank(), gmx_node_num(), returnCode);