diff --git a/src/backend/utils/cache/catcache.c b/src/backend/utils/cache/catcache.c
index ba95755867..57a5d8750d 100644
--- a/src/backend/utils/cache/catcache.c
+++ b/src/backend/utils/cache/catcache.c
@@ -1210,6 +1210,7 @@ SearchCatCacheInternal(CatCache *cache,
 	CatCTup    *ct;
 
 	/* Make sure we're in an xact, even if this ends up being a cache hit */
+	Assert(!in_processing_error());
 	Assert(IsTransactionState());
 
 	Assert(cache->cc_nkeys == nkeys);
diff --git a/src/backend/utils/error/elog.c b/src/backend/utils/error/elog.c
index 7790f6ab25..a49fec1b83 100644
--- a/src/backend/utils/error/elog.c
+++ b/src/backend/utils/error/elog.c
@@ -278,6 +278,31 @@ message_level_is_interesting(int elevel)
 	return false;
 }
 
+/*
+ * in_processing_error -- are we processing an error?
+ *
+ * This function exists to provde a check whether got called during processing
+ * an error. The functions that cannot run during that can use this check with
+ * an assertion.
+ */
+#ifdef USE_ASSERT_CHECKING
+bool
+in_processing_error(void)
+{
+	ErrorData  *edata;
+
+	/* We are not processing any ereport */
+	if (recursion_depth == 0)
+		return false;
+
+	/* If we doesn't set any error data yet, assume it's an error */
+	if (errordata_stack_depth == -1)
+		return true;
+
+	edata = &errordata[errordata_stack_depth];
+	return (edata->elevel >= ERROR);
+}
+#endif
 
 /*
  * in_error_recursion_trouble --- are we at risk of infinite error recursion?
diff --git a/src/include/utils/elog.h b/src/include/utils/elog.h
index 3c0e57621f..6cc4dec18a 100644
--- a/src/include/utils/elog.h
+++ b/src/include/utils/elog.h
@@ -439,6 +439,10 @@ extern void DebugFileOpen(void);
 extern char *unpack_sql_state(int sql_state);
 extern bool in_error_recursion_trouble(void);
 
+#ifdef USE_ASSERT_CHECKING
+extern bool in_processing_error(void);
+#endif
+
 #ifdef HAVE_SYSLOG
 extern void set_syslog_parameters(const char *ident, int facility);
 #endif
