Skip to content
Snippets Groups Projects

Issue #3215299: JMESpath exceptions should be exposed to the user

Files
4
@@ -2,7 +2,6 @@
namespace Drupal\feeds_ex\Feeds\Parser;
use Drupal\Component\Utility\Html;
use Drupal\Core\Logger\RfcLogLevel;
use Drupal\feeds\FeedInterface;
use Drupal\feeds\Result\FetcherResultInterface;
@@ -128,14 +127,31 @@ class JmesPathParser extends JsonParserBase {
* {@inheritdoc}
*/
protected function executeSourceExpression($machine_name, $expression, $row) {
$result = $this->search($expression, $row);
try {
$result = $this->search($expression, $row);
}
catch (\Exception $e) {
// There was an error executing this expression, transform it to a runtime
// exception, so that it gets properly catched by Feeds.
throw new \RuntimeException($e->getMessage());
}
if (is_object($result)) {
$result = (array) $result;
}
if (is_scalar($result) || empty($result)) {
if (!is_array($result)) {
return $result;
}
$count = count($result);
if ($count === 0) {
return;
}
// Return a single value if there's only one value.
return count($result) === 1 ? reset($result) : $result;
return count($result) === 1 ? reset($result) : array_values($result);
}
/**
@@ -151,11 +167,39 @@ class JmesPathParser extends JsonParserBase {
$this->search($expression, []);
}
catch (SyntaxErrorException $e) {
// Remove newlines after nl2br() to make testing easier.
return str_replace("\n", '', nl2br(Html::escape(trim($e->getMessage()))));
return $this->formatSyntaxError($e->getMessage());
}
}
/**
* Formats a syntax error message with HTML.
*
* A syntax error message can be for example:
* @code
* items[].join(`__`,[title,description)
* ^
* @endcode
*
* @param string $message
* The message to format.
*
* @return string
* The HTML formatted message.
*/
protected function formatSyntaxError($message) {
$message = trim($message);
$message = nl2br($message);
// Spaces in the error message can be used to point to a specific
// character in the line above.
$message = str_replace(' ', '  ', $message);
// Remove newlines to make testing easier.
$message = str_replace("\n", '', $message);
// Return the message between <pre>-tags so that the error message can be
// displayed correctly. Else the double spaces may not get displayed.
return '<pre>' . $message . '</pre>';
}
/**
* {@inheritdoc}
*/
Loading