bool isPathNotFoundError(const Error& error) { #ifdef _WIN32 return error.code() == boost::system::windows_error::path_not_found; #else return error.code() == boost::system::errc::no_such_file_or_directory; #endif }
void ErrorTest::testOperator() { Error e1( "e1", 2 ); Error e2 = e1; QCOMPARE( e1.message(), e2.message() ); QCOMPARE( e1.code(), e2.code() ); Error error; error = Error( "test error" ); QCOMPARE( error.message(), QString( "test error" ) ); QCOMPARE( error.code(), ( int )error.code() ); }
void reportHistoryAccessError(const std::string& context, const FilePath& historyFilePath, const Error& error) { // always log LOG_ERROR(error); // default summary std::string summary = error.summary(); // if the file exists and we still got no such file or directory // then it is almost always permission denied. this seems to happen // somewhat frequently on linux systems where the user was root for // an operation and ended up writing a .Rhistory if (historyFilePath.exists() && (error.code() == boost::system::errc::no_such_file_or_directory)) { summary = "permission denied (is the .Rhistory file owned by root?)"; } // notify the user std::string path = createAliasedPath(historyFilePath); std::string errmsg = context + " " + path + ": " + summary; REprintf(("Error attempting to " + errmsg + "\n").c_str()); }
Error system(const std::string& command, std::string* pOutput) { r::exec::RFunction system("system", command); system.addParam("intern", true); system.addParam("ignore.stderr", true); // call it Error error = system.call(pOutput); if (error) { // if it is NoDataAvailable this means empty output if (error.code() == r::errc::NoDataAvailableError) { pOutput->clear(); return Success(); } else { return error; } } else { return Success(); } }
void setJsonRpcResponse(const core::json::JsonRpcResponse& jsonRpcResponse, core::http::Response* pResponse) { // no cache! pResponse->setNoCacheHeaders(); // set content type if necessary (allows callers to override the // default application/json content-type, which is necessary in some // circumstances such as returning results to the GWT FileUpload widget // (which expects text/html) if (pResponse->contentType().empty()) pResponse->setContentType(kJsonContentType) ; // set body std::stringstream responseStream ; jsonRpcResponse.write(responseStream); Error error = pResponse->setBody(responseStream); // report error to client if one occurred if (error) { LOG_ERROR(error); pResponse->setError(http::status::InternalServerError, error.code().message()); } }
void JsonRpcResponse::setError(const Error& error, const json::Value& clientInfo) { // remove result response_.erase(kRpcResult); response_.erase(kRpcAsyncHandle); const boost::system::error_code& ec = error.code(); if ( ec.category() == jsonRpcCategory() ) { setError(ec); } else { // execution error json::Object jsonError ; copyErrorCodeToJsonError(errc::ExecutionError, &jsonError); // populate sub-error field with error details json::Object executionError; executionError["code"] = ec.value(); std::string errorCategoryName = ec.category().name(); executionError["category"] = errorCategoryName; std::string errorMessage = ec.message(); executionError["message"] = errorMessage; jsonError["error"] = executionError; if (!clientInfo.is_null()) { jsonError["client_info"] = clientInfo; } // set error setField(kRpcError, jsonError); } }
TEST(ResultTest, TestSetError) { bool fired = false; Json::Value id("8"); Result res(id); res.signal_state_changed.connect([&fired](){ fired = true; }); res.set_error(Error(42, "Malfunction")); ASSERT_EQ(true, fired); Error e = res.error(); ASSERT_EQ(42, e.code()); ASSERT_EQ(std::string("Malfunction"), e.message()); }
Error scanRegistryForRTools(std::vector<RToolsInfo>* pRTools) { core::system::RegistryKey regKey; Error error = regKey.open(HKEY_LOCAL_MACHINE, "Software\\R-core\\Rtools", KEY_READ | KEY_WOW64_32KEY); if (error) { if (error.code() != boost::system::errc::no_such_file_or_directory) return error; else return Success(); } std::vector<std::string> keys = regKey.keyNames(); for (int i = 0; i < keys.size(); i++) { std::string name = keys.at(i); core::system::RegistryKey verKey; error = verKey.open(regKey.handle(), name, KEY_READ | KEY_WOW64_32KEY); if (error) { LOG_ERROR(error); continue; } std::string installPath = verKey.getStringValue("InstallPath", ""); if (!installPath.empty()) { std::string utf8InstallPath = string_utils::systemToUtf8(installPath); RToolsInfo toolsInfo(name, FilePath(utf8InstallPath)); if (toolsInfo.isStillInstalled()) { if (toolsInfo.isRecognized()) pRTools->push_back(toolsInfo); else LOG_WARNING_MESSAGE("Unknown Rtools version: " + name); } } } return Success(); }
Error Settings::initialize(const FilePath& filePath) { settingsFile_ = filePath ; settingsMap_.clear() ; Error error = core::readStringMapFromFile(settingsFile_, &settingsMap_) ; if (error) { // we don't consider file-not-found and error because it is a // common initialization case if (error.code() != boost::system::errc::no_such_file_or_directory) { error.addProperty("settings-file", settingsFile_); return error ; } } return Success() ; }
void ProjectContext::fileMonitorTermination(const Error& error) { // always log error if (error) LOG_ERROR(error); // if we have a file monitor then unwind it if (hasFileMonitor_) { // do this only once hasFileMonitor_ = false; // notify end-user if this was an error condition if (error) { // base error message boost::system::error_code ec = error.code(); std::string dir = module_context::createAliasedPath(directory()); boost::format fmt( "\nWarning message:\n" "File monitoring failed for project at \"%1%\"\n" "Error %2% (%3%)"); std::string msg = boost::str(fmt % dir % ec.value() % ec.message()); // enumeration of affected features if (!monitorSubscribers_.empty()) msg.append("\nFeatures disabled:"); for(std::size_t i=0; i<monitorSubscribers_.size(); ++i) { if (i > 0) msg.append(","); msg.append(" "); msg.append(monitorSubscribers_[i]); } // write to console module_context::consoleWriteError(msg); } // notify subscribers onMonitoringDisabled_(); } }
void setFile(const FilePath& filePath, const Request& request, const Filter& filter) { // ensure that the file exists if (!filePath.exists()) { setError(http::status::NotFound, request.uri() + " not found"); return; } // set content type setContentType(filePath.mimeContentType()); // gzip if possible if (request.acceptsEncoding(kGzipEncoding)) setContentEncoding(kGzipEncoding); // set body from file Error error = setBody(filePath, filter); if (error) setError(status::InternalServerError, error.code().message()); }
void reportError(const std::string& action, const std::string& context, const Error& error, const ErrorLocation& location, const boost::function<void(const char*)>& reportFunction = boost::function<void(const char*)>()) { // build the message std::string message = "Error " + action + " session"; if (!context.empty()) message += std::string(" (" + context + ")"); // add context to error and log it Error serializationError = error ; serializationError.addProperty("context", message); core::log::logError(serializationError, location); // notify end-user std::string report = message + ": " + error.code().message() + "\n"; if (reportFunction) reportFunction(report.c_str()); else REprintf(report.c_str()); }
Error openDocument(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { // params std::string path; Error error = json::readParam(request.params, 0, &path); if (error) return error ; std::string type; error = json::readParam(request.params, 1, &type); if (error) return error ; std::string encoding; error = json::readParam(request.params, 2, &encoding); if (error && error.code() != core::json::errc::ParamTypeMismatch) return error ; if (encoding.empty()) encoding = ::locale2charset(NULL); // ensure the file exists FilePath documentPath = module_context::resolveAliasedPath(path); if (!documentPath.exists()) { return systemError(boost::system::errc::no_such_file_or_directory, ERROR_LOCATION); } // ensure the file is not binary if (!module_context::isTextFile(documentPath)) { Error error = systemError(boost::system::errc::illegal_byte_sequence, ERROR_LOCATION); pResponse->setError(error, "File is binary rather than text so cannot " "be opened by the source editor."); return Success(); } // set the doc contents to the specified file boost::shared_ptr<SourceDocument> pDoc(new SourceDocument(type)) ; pDoc->setEncoding(encoding); error = pDoc->setPathAndContents(path, false); if (error) { error = pDoc->setPathAndContents(path, true); if (error) return error ; module_context::consoleWriteError( "Not all characters in " + documentPath.absolutePath() + " could be decoded using " + encoding + ". To try a " "different encoding, choose \"File | Reopen with " "Encoding...\" from the main menu."); } // recover durable properties if they are available json::Object properties; error = source_database::getDurableProperties(path, &properties); if (!error) pDoc->editProperties(properties); else LOG_ERROR(error); // set relative order (client will receive docs in relative order on init) pDoc->setRelativeOrder(numSourceDocuments() + 1); // write to the source_database error = sourceDatabasePutWithUpdatedContents(pDoc); if (error) return error; // return the doc json::Object jsonDoc; writeDocToJson(pDoc, &jsonDoc); pResponse->setResult(jsonDoc); return Success(); }
Error processEvent(FileEventContext* pContext, struct inotify_event* pEvent, std::vector<FileChangeEvent>* pFileChanges) { // determine event type FileChangeEvent::Type eventType = FileChangeEvent::None; if (pEvent->mask & IN_CREATE) eventType = FileChangeEvent::FileAdded; else if (pEvent->mask & IN_DELETE) eventType = FileChangeEvent::FileRemoved; else if (pEvent->mask & IN_MODIFY) eventType = FileChangeEvent::FileModified; else if (pEvent->mask & IN_MOVED_TO) eventType = FileChangeEvent::FileAdded; else if (pEvent->mask & IN_MOVED_FROM) eventType = FileChangeEvent::FileRemoved; // return event if we got a valid event type and the event applies to a // child of the monitored directory (len == 0 occurs for root element) if ((eventType != FileChangeEvent::None) && (pEvent->len > 0)) { // find the FileInfo for this wd (ignore if we can't find one) Watch watch = pContext->watches.find(pEvent->wd); if (watch.empty()) return Success(); // get an iterator to the parent dir tree<FileInfo>::iterator parentIt = impl::findFile( pContext->fileTree.begin(), pContext->fileTree.end(), watch.path); // if we can't find a parent then return (this directory may have // been excluded from scanning due to a filter) if (parentIt == pContext->fileTree.end()) return Success(); // get file info FilePath filePath = FilePath(parentIt->absolutePath()).complete( pEvent->name); // if the file exists then collect as many extended attributes // as necessary -- otherwise just record path and dir status FileInfo fileInfo; if (filePath.exists()) { fileInfo = FileInfo(filePath, filePath.isSymlink()); } else { fileInfo = FileInfo(filePath.absolutePath(), pEvent->mask & IN_ISDIR); } // if this doesn't meet the filter then ignore if (pContext->filter && !pContext->filter(fileInfo)) return Success(); // handle the various types of actions switch(eventType) { case FileChangeEvent::FileRemoved: { // generate events FileChangeEvent event(FileChangeEvent::FileRemoved, fileInfo); std::vector<FileChangeEvent> removeEvents; impl::processFileRemoved(parentIt, event, pContext->recursive, &pContext->fileTree, &removeEvents); // for each directory remove event remove any watches we have for it BOOST_FOREACH(const FileChangeEvent& event, removeEvents) { if (event.fileInfo().isDirectory()) { Watch watch = pContext->watches.find( event.fileInfo().absolutePath()); if (!watch.empty()) { removeWatch(pContext->fd, watch); pContext->watches.erase(watch); } } } // copy to the target events std::copy(removeEvents.begin(), removeEvents.end(), std::back_inserter(*pFileChanges)); break; } case FileChangeEvent::FileAdded: { FileChangeEvent event(FileChangeEvent::FileAdded, fileInfo); Error error = impl::processFileAdded(parentIt, event, pContext->recursive, pContext->filter, addWatchFunction(pContext), &pContext->fileTree, pFileChanges); // log the error if it wasn't no such file/dir (this can happen // in the normal course of business if a file is deleted between // the time the change is detected and we try to inspect it) if (error && (error.code() != boost::system::errc::no_such_file_or_directory)) { LOG_ERROR(error); } break; } case FileChangeEvent::FileModified: { FileChangeEvent event(FileChangeEvent::FileModified, fileInfo); impl::processFileModified(parentIt, event, &pContext->fileTree, pFileChanges); break; } case FileChangeEvent::None: break; } }
void manualErrorCheckAfter(const glbinding::AbstractFunction & function) { Error error = Error::get(); if (!error) return; if (!Registry::current().isInitialized()) { debug() << "Error during initialization: " << error.name(); return; } if (!DebugMessage::isFallbackImplementation()) return; std::stringstream stream; stream << function.name() << " generated " << error.name(); DebugMessage::insertMessage(GL_DEBUG_SOURCE_API_ARB, GL_DEBUG_TYPE_ERROR_ARB, static_cast<unsigned int>(error.code()), GL_DEBUG_SEVERITY_HIGH_ARB, stream.str()); }
Error openDocument(const json::JsonRpcRequest& request, json::JsonRpcResponse* pResponse) { // params std::string path; Error error = json::readParam(request.params, 0, &path); if (error) return error ; std::string type; error = json::readParam(request.params, 1, &type); if (error) return error ; std::string encoding; error = json::readParam(request.params, 2, &encoding); if (error && error.code() != core::json::errc::ParamTypeMismatch) return error ; if (encoding.empty()) encoding = ::locale2charset(NULL); // ensure the file exists FilePath documentPath = module_context::resolveAliasedPath(path); if (!documentPath.exists()) { return systemError(boost::system::errc::no_such_file_or_directory, ERROR_LOCATION); } // set the doc contents to the specified file boost::shared_ptr<SourceDocument> pDoc(new SourceDocument(type)) ; pDoc->setEncoding(encoding); error = pDoc->setPathAndContents(path, false); if (error) { error = pDoc->setPathAndContents(path, true); if (error) return error ; r::exec::warning("Not all characters in " + documentPath.absolutePath() + " could be decoded using " + encoding + ". To try a " "different encoding, choose \"File | Reopen with " "Encoding...\" from the main menu."); r::exec::printWarnings(); } // recover durable properties if they are available json::Object properties; error = source_database::getDurableProperties(path, &properties); if (!error) pDoc->editProperties(properties); else LOG_ERROR(error); // write to the source_database error = sourceDatabasePutWithUpdatedContents(pDoc); if (error) return error; // return the doc json::Object jsonDoc; pDoc->writeToJson(&jsonDoc); pResponse->setResult(jsonDoc); return Success(); }
void Response::setError(const Error& error) { setError(status::InternalServerError, error.code().message()); }