diff --git a/src/backend/utils/adt/misc.c b/src/backend/utils/adt/misc.c
index 4453e818c0074fbfc80cfd954202f6bedab5e09a..478f203273fac7ed677e666148a4c5259717022f 100644
--- a/src/backend/utils/adt/misc.c
+++ b/src/backend/utils/adt/misc.c
@@ -287,9 +287,12 @@ pg_tablespace_location(PG_FUNCTION_ARGS)
 	 */
 	snprintf(sourcepath, sizeof(sourcepath), "pg_tblspc/%u", tablespaceOid);
 	rllen =readlink(sourcepath, targetpath, sizeof(targetpath));
-	if (rllen < 0 || rllen >= sizeof(targetpath))
+	if (rllen < 0)
 		ereport(ERROR,
 				(errmsg("could not read symbolic link \"%s\": %m", sourcepath)));
+	else if (rllen >= sizeof(targetpath))
+		ereport(ERROR,
+				(errmsg("symbolic link \"%s\" target is too long", sourcepath)));
 	targetpath[rllen] = '\0';
 
 	PG_RETURN_TEXT_P(cstring_to_text(targetpath));