Throw IcingaException rather than Exception

fixes #7014
This commit is contained in:
Alexander Klimov 2014-08-27 16:03:15 +02:00
parent 7ff51caed0
commit 45638b218c
33 changed files with 240 additions and 157 deletions

View File

@ -5,7 +5,7 @@
namespace Icinga\Clicommands; namespace Icinga\Clicommands;
use Icinga\Cli\Command; use Icinga\Cli\Command;
use Exception; use Icinga\Exception\IcingaException;
class WebCommand extends Command class WebCommand extends Command
{ {
@ -13,11 +13,11 @@ class WebCommand extends Command
{ {
$minVersion = '5.4.0'; $minVersion = '5.4.0';
if (version_compare(PHP_VERSION, $minVersion) < 0) { if (version_compare(PHP_VERSION, $minVersion) < 0) {
throw new Exception(sprintf( throw new IcingaException(
'You are running PHP %s, internal webserver requires %s.', 'You are running PHP %s, internal webserver requires %s.',
PHP_VERSION, PHP_VERSION,
$minVersion $minVersion
)); );
} }
$fork = $this->params->get('daemonize'); $fork = $this->params->get('daemonize');
@ -27,12 +27,12 @@ class WebCommand extends Command
// TODO: Sanity check!! // TODO: Sanity check!!
if ($socket === null) { if ($socket === null) {
$socket = '0.0.0.0:80'; $socket = '0.0.0.0:80';
// throw new Exception('Socket is required'); // throw new IcingaException('Socket is required');
} }
if ($basedir === null) { if ($basedir === null) {
$basedir = dirname(ICINGAWEB_APPDIR) . '/public'; $basedir = dirname(ICINGAWEB_APPDIR) . '/public';
if (! file_exists($basedir) || ! is_dir($basedir)) { if (! file_exists($basedir) || ! is_dir($basedir)) {
throw new Exception('Basedir is required'); throw new IcingaException('Basedir is required');
} }
} }
$basedir = realpath($basedir); $basedir = realpath($basedir);
@ -68,7 +68,7 @@ class WebCommand extends Command
{ {
$pid = pcntl_fork(); $pid = pcntl_fork();
if ($pid == -1) { if ($pid == -1) {
throw new Exception('Could not fork'); throw new IcingaException('Could not fork');
} else if ($pid) { } else if ($pid) {
echo $this->screen->colorize('[OK]') echo $this->screen->colorize('[OK]')
. " Icinga Web server forked successfully\n"; . " Icinga Web server forked successfully\n";

View File

@ -12,6 +12,7 @@ use Icinga\Form\Dashboard\AddUrlForm;
use Icinga\Exception\NotReadableError; use Icinga\Exception\NotReadableError;
use Icinga\Exception\ConfigurationError; use Icinga\Exception\ConfigurationError;
use Icinga\Web\Controller\ActionController; use Icinga\Web\Controller\ActionController;
use Icinga\Exception\IcingaException;
/** /**
* Handle creation, removal and displaying of dashboards, panes and components * Handle creation, removal and displaying of dashboards, panes and components
@ -42,7 +43,7 @@ class DashboardController extends ActionController
} }
$dashboard->readConfig($dashboardConfig); $dashboard->readConfig($dashboardConfig);
} catch (NotReadableError $e) { } catch (NotReadableError $e) {
Logger::error(new Exception('Cannot load dashboard configuration. An exception was thrown:', 0, $e)); Logger::error(new IcingaException('Cannot load dashboard configuration. An exception was thrown:', $e));
return null; return null;
} }
return $dashboard; return $dashboard;

View File

@ -157,7 +157,7 @@ class LdapBackendForm extends BaseBackendForm
$testConn->assertAuthenticationPossible(); $testConn->assertAuthenticationPossible();
/* /*
if ($testConn->count() === 0) { if ($testConn->count() === 0) {
throw new Exception('No Users Found On Directory Server'); throw new IcingaException('No Users Found On Directory Server');
} }
*/ */
} catch (Exception $exc) { } catch (Exception $exc) {

View File

@ -14,6 +14,7 @@ use Icinga\Exception\NotReadableError;
use Icinga\Logger\Logger; use Icinga\Logger\Logger;
use Icinga\Util\DateTimeFactory; use Icinga\Util\DateTimeFactory;
use Icinga\Util\Translator; use Icinga\Util\Translator;
use Icinga\Exception\IcingaException;
/** /**
* This class bootstraps a thin Icinga application layer * This class bootstraps a thin Icinga application layer
@ -332,7 +333,7 @@ abstract class ApplicationBootstrap
try { try {
$this->moduleManager->loadEnabledModules(); $this->moduleManager->loadEnabledModules();
} catch (NotReadableError $e) { } catch (NotReadableError $e) {
Logger::error(new Exception('Cannot load enabled modules. An exception was thrown:', 0, $e)); Logger::error(new IcingaException('Cannot load enabled modules. An exception was thrown:', $e));
} }
return $this; return $this;
} }
@ -369,7 +370,7 @@ abstract class ApplicationBootstrap
try { try {
$this->config = Config::app(); $this->config = Config::app();
} catch (NotReadableError $e) { } catch (NotReadableError $e) {
Logger::error(new Exception('Cannot load application configuration. An exception was thrown:', 0, $e)); Logger::error(new IcingaException('Cannot load application configuration. An exception was thrown:', $e));
$this->config = new Zend_Config(array()); $this->config = new Zend_Config(array());
} }
return $this; return $this;
@ -417,7 +418,7 @@ abstract class ApplicationBootstrap
ResourceFactory::setConfig($config); ResourceFactory::setConfig($config);
} catch (NotReadableError $e) { } catch (NotReadableError $e) {
Logger::error( Logger::error(
new Exception('Cannot load resource configuration. An exception was thrown:', 0, $e) new IcingaException('Cannot load resource configuration. An exception was thrown:', $e)
); );
} }

View File

@ -19,6 +19,7 @@ use Icinga\Web\Widget;
use Icinga\Web\Widget\Dashboard\Pane; use Icinga\Web\Widget\Dashboard\Pane;
use Icinga\Util\File; use Icinga\Util\File;
use Icinga\Exception\ProgrammingError; use Icinga\Exception\ProgrammingError;
use Icinga\Exception\IcingaException;
/** /**
* Module handling * Module handling
@ -630,8 +631,9 @@ class Module
protected function providePermission($name, $description) protected function providePermission($name, $description)
{ {
if ($this->providesPermission($name)) { if ($this->providesPermission($name)) {
throw new Exception( throw new IcingaException(
sprintf('Cannot provide permission "%s" twice', $name) 'Cannot provide permission "%s" twice',
$name
); );
} }
$this->permissionList[$name] = (object) array( $this->permissionList[$name] = (object) array(
@ -651,8 +653,9 @@ class Module
protected function provideRestriction($name, $description) protected function provideRestriction($name, $description)
{ {
if ($this->providesRestriction($name)) { if ($this->providesRestriction($name)) {
throw new Exception( throw new IcingaException(
sprintf('Cannot provide restriction "%s" twice', $name) 'Cannot provide restriction "%s" twice',
$name
); );
} }
$this->restrictionList[$name] = (object) array( $this->restrictionList[$name] = (object) array(

View File

@ -11,6 +11,7 @@ use Icinga\Exception\AuthenticationException;
use Exception; use Exception;
use Zend_Db_Expr; use Zend_Db_Expr;
use Zend_Db_Select; use Zend_Db_Select;
use Icinga\Exception\IcingaException;
class DbUserBackend extends UserBackend class DbUserBackend extends UserBackend
{ {
@ -60,7 +61,10 @@ class DbUserBackend extends UserBackend
return false; return false;
} }
if ($salt === '') { if ($salt === '') {
throw new Exception('Cannot find salt for user ' . $user->getUsername()); throw new IcingaException(
'Cannot find salt for user %s',
$user->getUsername()
);
} }
$select = new Zend_Db_Select($this->conn->getConnection()); $select = new Zend_Db_Select($this->conn->getConnection());

View File

@ -13,6 +13,7 @@ use Icinga\Exception\NotReadableError;
use Icinga\Application\Config as IcingaConfig; use Icinga\Application\Config as IcingaConfig;
use Icinga\User\Preferences; use Icinga\User\Preferences;
use Icinga\User\Preferences\PreferencesStore; use Icinga\User\Preferences\PreferencesStore;
use Icinga\Exception\IcingaException;
class Manager class Manager
{ {
@ -55,7 +56,11 @@ class Manager
$config = IcingaConfig::app(); $config = IcingaConfig::app();
} catch (NotReadableError $e) { } catch (NotReadableError $e) {
Logger::error( Logger::error(
new Exception('Cannot load preferences for user "' . $username . '". An exception was thrown', 0, $e) new IcingaException(
'Cannot load preferences for user "%s". An exception was thrown',
$username,
$e
)
); );
$config = new Zend_Config(array()); $config = new Zend_Config(array());
} }
@ -68,8 +73,10 @@ class Manager
$preferences = new Preferences($preferencesStore->load()); $preferences = new Preferences($preferencesStore->load());
} catch (NotReadableError $e) { } catch (NotReadableError $e) {
Logger::error( Logger::error(
new Exception( new IcingaException(
'Cannot load preferences for user "' . $username . '". An exception was thrown', 0, $e 'Cannot load preferences for user "%s". An exception was thrown',
$username,
$e
) )
); );
$preferences = new Preferences(); $preferences = new Preferences();

View File

@ -9,6 +9,7 @@ use Icinga\Chart\Legend;
use Icinga\Chart\Palette; use Icinga\Chart\Palette;
use Icinga\Chart\Primitive\Drawable; use Icinga\Chart\Primitive\Drawable;
use Icinga\Chart\SVGRenderer; use Icinga\Chart\SVGRenderer;
use Icinga\Exception\IcingaException;
/** /**
* Base class for charts, extended by all other Chart classes. * Base class for charts, extended by all other Chart classes.
@ -87,15 +88,15 @@ abstract class Chart implements Drawable
* *
* Render this graph and return the created SVG * Render this graph and return the created SVG
* *
* @return string The SVG created by the SvgRenderer * @return string The SVG created by the SvgRenderer
* *
* @throws Exception Thrown wen the dataset is not valid for this graph * @throws IcingaException Thrown wen the dataset is not valid for this graph
* @see SVGRenderer::render * @see SVGRenderer::render
*/ */
public function render() public function render()
{ {
if (!$this->isValidDataFormat()) { if (!$this->isValidDataFormat()) {
throw new Exception('Dataset for graph doesn\'t have the proper structure'); throw new IcingaException('Dataset for graph doesn\'t have the proper structure');
} }
$this->build(); $this->build();

View File

@ -7,6 +7,7 @@ namespace Icinga\Chart\Inline;
use Icinga\Chart\PieChart as PieChartRenderer; use Icinga\Chart\PieChart as PieChartRenderer;
use Imagick; use Imagick;
use Exception; use Exception;
use Icinga\Exception\IcingaException;
/** /**
* Draw an inline pie-chart directly from the available request parameters. * Draw an inline pie-chart directly from the available request parameters.
@ -33,7 +34,7 @@ class PieChart extends Inline
{ {
if (! class_exists('Imagick')) { if (! class_exists('Imagick')) {
// TODO: This is quick & dirty. 404? // TODO: This is quick & dirty. 404?
throw new Exception('Cannot render PNGs without Imagick'); throw new IcingaException('Cannot render PNGs without Imagick');
} }
$image = new Imagick(); $image = new Imagick();
$image->readImageBlob($this->render(false)); $image->readImageBlob($this->render(false));

View File

@ -5,6 +5,7 @@
namespace Icinga\Cli; namespace Icinga\Cli;
use Icinga\Cli\Screen; use Icinga\Cli\Screen;
use Icinga\Exception\IcingaException;
// @see http://en.wikipedia.org/wiki/ANSI_escape_code // @see http://en.wikipedia.org/wiki/ANSI_escape_code
@ -74,7 +75,10 @@ class AnsiScreen extends Screen
protected function fgColor($color) protected function fgColor($color)
{ {
if (! array_key_exists($color, $this->fgColors)) { if (! array_key_exists($color, $this->fgColors)) {
throw new \Exception(sprintf('There is no such foreground color: %s', $color)); throw new IcingaException(
'There is no such foreground color: %s',
$color
);
} }
return $this->fgColors[$color]; return $this->fgColors[$color];
} }
@ -82,7 +86,10 @@ class AnsiScreen extends Screen
protected function bgColor($color) protected function bgColor($color)
{ {
if (! array_key_exists($color, $this->bgColors)) { if (! array_key_exists($color, $this->bgColors)) {
throw new \Exception(sprintf('There is no such background color: %s', $color)); throw new IcingaException(
'There is no such background color: %s',
$color
);
} }
return $this->bgColors[$color]; return $this->bgColors[$color];
} }

View File

@ -10,6 +10,7 @@ use Icinga\Cli\Params;
use Icinga\Application\Config; use Icinga\Application\Config;
use Icinga\Application\ApplicationBootstrap as App; use Icinga\Application\ApplicationBootstrap as App;
use Exception; use Exception;
use Icinga\Exception\IcingaException;
abstract class Command abstract class Command
{ {
@ -123,7 +124,7 @@ abstract class Command
public function fail($msg) public function fail($msg)
{ {
throw new Exception($msg); throw new IcingaException('%s', $msg);
} }
public function getDefaultActionName() public function getDefaultActionName()

View File

@ -11,6 +11,7 @@ use Icinga\Data\Filter\FilterExpression;
use Icinga\Data\Filter\FilterOr; use Icinga\Data\Filter\FilterOr;
use Icinga\Data\Filter\FilterAnd; use Icinga\Data\Filter\FilterAnd;
use Icinga\Data\Filter\FilterNot; use Icinga\Data\Filter\FilterNot;
use Icinga\Exception\IcingaException;
use Zend_Db_Select; use Zend_Db_Select;
/** /**
@ -124,7 +125,10 @@ class DbQuery extends SimpleQuery
$op = ' AND '; $op = ' AND ';
$str .= ' NOT '; $str .= ' NOT ';
} else { } else {
throw new \Exception('Cannot render filter: ' . $filter); throw new IcingaException(
'Cannot render filter: %s',
$filter
);
} }
$parts = array(); $parts = array();
if (! $filter->isEmpty()) { if (! $filter->isEmpty()) {
@ -177,7 +181,7 @@ class DbQuery extends SimpleQuery
if (! $value) { if (! $value) {
/* /*
NOTE: It's too late to throw exceptions, we might finish in __toString NOTE: It's too late to throw exceptions, we might finish in __toString
throw new \Exception(sprintf( throw new IcingaException(sprintf(
'"%s" is not a valid time expression', '"%s" is not a valid time expression',
$value $value
)); ));

View File

@ -9,6 +9,7 @@ use Icinga\Data\Filter\Filter;
use Icinga\Web\Paginator\Adapter\QueryAdapter; use Icinga\Web\Paginator\Adapter\QueryAdapter;
use Zend_Paginator; use Zend_Paginator;
use Exception; use Exception;
use Icinga\Exception\IcingaException;
class SimpleQuery implements QueryInterface, Queryable class SimpleQuery implements QueryInterface, Queryable
{ {
@ -158,7 +159,7 @@ class SimpleQuery implements QueryInterface, Queryable
public function setOrderColumns(array $orderColumns) public function setOrderColumns(array $orderColumns)
{ {
throw new Exception('This function does nothing and will be removed'); throw new IcingaException('This function does nothing and will be removed');
} }
/** /**

View File

@ -5,6 +5,7 @@
namespace Icinga\Logger\Writer; namespace Icinga\Logger\Writer;
use Exception; use Exception;
use Icinga\Exception\IcingaException;
use Zend_Config; use Zend_Config;
use Icinga\Util\File; use Icinga\Util\File;
use Icinga\Logger\Logger; use Icinga\Logger\Logger;
@ -68,7 +69,7 @@ class FileWriter extends LogWriter
* *
* @return string The string representation of the severity * @return string The string representation of the severity
* *
* @throws Exception In case the given severity is unknown * @throws IcingaException In case the given severity is unknown
*/ */
protected function getSeverityString($severity) protected function getSeverityString($severity)
{ {
@ -82,7 +83,10 @@ class FileWriter extends LogWriter
case Logger::$DEBUG: case Logger::$DEBUG:
return '- DEBUG -'; return '- DEBUG -';
default: default:
throw new Exception('Unknown severity "' . $severity . '"'); throw new IcingaException(
'Unknown severity "%s"',
$severity
);
} }
} }

View File

@ -9,6 +9,7 @@ use Zend_Config;
use Icinga\Logger\Logger; use Icinga\Logger\Logger;
use Icinga\Logger\LogWriter; use Icinga\Logger\LogWriter;
use Icinga\Exception\ConfigurationError; use Icinga\Exception\ConfigurationError;
use Icinga\Exception\IcingaException;
/** /**
* Class to write messages to syslog * Class to write messages to syslog
@ -72,7 +73,10 @@ class SyslogWriter extends LogWriter
); );
if (!array_key_exists($severity, $priorities)) { if (!array_key_exists($severity, $priorities)) {
throw new Exception('Severity "' . $severity . '" cannot be mapped to a valid syslog priority'); throw new IcingaException(
'Severity "%s" cannot be mapped to a valid syslog priority',
$severity
);
} }
$this->open(); $this->open();

View File

@ -4,6 +4,8 @@
namespace Icinga\Protocol\Ldap; namespace Icinga\Protocol\Ldap;
use Icinga\Exception\IcingaException;
/** /**
* Search class * Search class
* *
@ -82,12 +84,10 @@ class Query
public function limit($count = null, $offset = null) public function limit($count = null, $offset = null)
{ {
if (! preg_match('~^\d+~', $count . $offset)) { if (! preg_match('~^\d+~', $count . $offset)) {
throw new Exception( throw new IcingaException(
sprintf( 'Got invalid limit: %s, %s',
'Got invalid limit: %s, %s', $count,
$count, $offset
$offset
)
); );
} }
$this->limit_count = (int) $count; $this->limit_count = (int) $count;
@ -316,7 +316,7 @@ class Query
{ {
$parts = array(); $parts = array();
if (! isset($this->filters['objectClass']) || $this->filters['objectClass'] === null) { if (! isset($this->filters['objectClass']) || $this->filters['objectClass'] === null) {
// throw new Exception('Object class is mandatory'); // throw new IcingaException('Object class is mandatory');
} }
foreach ($this->filters as $key => $value) { foreach ($this->filters as $key => $value) {
$parts[] = sprintf( $parts[] = sprintf(

View File

@ -4,6 +4,8 @@
namespace Icinga\Protocol\Ldap; namespace Icinga\Protocol\Ldap;
use Icinga\Exception\IcingaException;
/** /**
* This class is a special node object, representing your connections root node * This class is a special node object, representing your connections root node
* *
@ -95,16 +97,14 @@ class Root
/** /**
* @param $rdn * @param $rdn
* @return mixed * @return mixed
* @throws Exception * @throws IcingaException
*/ */
public function getChildByRDN($rdn) public function getChildByRDN($rdn)
{ {
if (!$this->hasChildRDN($rdn)) { if (!$this->hasChildRDN($rdn)) {
throw new Exception( throw new IcingaException(
sprintf( 'The child RDN "%s" is not available',
'The child RDN "%s" is not available', $rdn
$rdn
)
); );
} }
return $this->children[strtolower($rdn)]; return $this->children[strtolower($rdn)];
@ -154,28 +154,24 @@ class Root
/** /**
* @param $dn * @param $dn
* @return $this * @return $this
* @throws Exception * @throws IcingaException
*/ */
protected function assertSubDN($dn) protected function assertSubDN($dn)
{ {
$mydn = $this->getDN(); $mydn = $this->getDN();
$end = substr($dn, -1 * strlen($mydn)); $end = substr($dn, -1 * strlen($mydn));
if (strtolower($end) !== strtolower($mydn)) { if (strtolower($end) !== strtolower($mydn)) {
throw new Exception( throw new IcingaException(
sprintf( '"%s" is not a child of "%s"',
'"%s" is not a child of "%s"', $dn,
$dn, $mydn
$mydn
)
); );
} }
if (strlen($dn) === strlen($mydn)) { if (strlen($dn) === strlen($mydn)) {
throw new Exception( throw new IcingaException(
sprintf( '"%s" is not a child of "%s", they are equal',
'"%s" is not a child of "%s", they are equal', $dn,
$dn, $mydn
$mydn
)
); );
} }
return $this; return $this;

View File

@ -6,6 +6,7 @@ namespace Icinga\Protocol\Livestatus;
use Icinga\Application\Benchmark; use Icinga\Application\Benchmark;
use Exception; use Exception;
use Icinga\Exception\IcingaException;
/** /**
* Backend class managing handling MKI Livestatus connections * Backend class managing handling MKI Livestatus connections
@ -73,22 +74,18 @@ class Connection
$this->assertPhpExtensionLoaded('sockets'); $this->assertPhpExtensionLoaded('sockets');
if ($socket[0] === '/') { if ($socket[0] === '/') {
if (! is_writable($socket)) { if (! is_writable($socket)) {
throw new \Exception( throw new IcingaException(
sprintf( 'Cannot write to livestatus socket "%s"',
'Cannot write to livestatus socket "%s"', $socket
$socket
)
); );
} }
$this->socket_type = self::TYPE_UNIX; $this->socket_type = self::TYPE_UNIX;
$this->socket_path = $socket; $this->socket_path = $socket;
} else { } else {
if (! preg_match('~^tcp://([^:]+):(\d+)~', $socket, $m)) { if (! preg_match('~^tcp://([^:]+):(\d+)~', $socket, $m)) {
throw new \Exception( throw new IcingaException(
sprintf( 'Invalid TCP socket syntax: "%s"',
'Invalid TCP socket syntax: "%s"', $socket
$socket
)
); );
} }
// TODO: Better syntax checks // TODO: Better syntax checks
@ -156,17 +153,15 @@ class Connection
$length = (int) trim(substr($header, 4)); $length = (int) trim(substr($header, 4));
$body = $this->readFromSocket($length); $body = $this->readFromSocket($length);
if ($status !== 200) { if ($status !== 200) {
throw new Exception( throw new IcingaException(
sprintf( 'Problem while reading %d bytes from livestatus: %s',
'Problem while reading %d bytes from livestatus: %s', $length,
$length, $body
$body
)
); );
} }
$result = json_decode($body); $result = json_decode($body);
if ($result === null) { if ($result === null) {
throw new Exception('Got invalid response body from livestatus'); throw new IcingaException('Got invalid response body from livestatus');
} }
return $result; return $result;
@ -180,11 +175,9 @@ class Connection
while ($offset < $length) { while ($offset < $length) {
$data = socket_read($this->connection, $length - $offset); $data = socket_read($this->connection, $length - $offset);
if ($data === false) { if ($data === false) {
throw new Exception( throw new IcingaException(
sprintf( 'Failed to read from livestatus socket: %s',
'Failed to read from livestatus socket: %s', socket_strerror(socket_last_error($this->connection))
socket_strerror(socket_last_error($this->connection))
)
); );
} }
$size = strlen($data); $size = strlen($data);
@ -196,12 +189,10 @@ class Connection
} }
} }
if ($offset !== $length) { if ($offset !== $length) {
throw new \Exception( throw new IcingaException(
sprintf( 'Got only %d instead of %d bytes from livestatus socket',
'Got only %d instead of %d bytes from livestatus socket', $offset,
$offset, $length
$length
)
); );
} }
@ -212,7 +203,7 @@ class Connection
{ {
$res = socket_write($this->connection, $data); $res = socket_write($this->connection, $data);
if ($res === false) { if ($res === false) {
throw new \Exception('Writing to livestatus socket failed'); throw new IcingaException('Writing to livestatus socket failed');
} }
return true; return true;
} }
@ -220,11 +211,9 @@ class Connection
protected function assertPhpExtensionLoaded($name) protected function assertPhpExtensionLoaded($name)
{ {
if (! extension_loaded($name)) { if (! extension_loaded($name)) {
throw new \Exception( throw new IcingaException(
sprintf( 'The extension "%s" is not loaded',
'The extension "%s" is not loaded', $name
$name
)
); );
} }
} }
@ -250,13 +239,11 @@ class Connection
$this->connection = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); $this->connection = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (! @socket_connect($this->connection, $this->socket_host, $this->socket_port)) { if (! @socket_connect($this->connection, $this->socket_host, $this->socket_port)) {
throw new \Exception( throw new IcingaException(
sprintf( 'Cannot connect to livestatus TCP socket "%s:%d": %s',
'Cannot connect to livestatus TCP socket "%s:%d": %s', $this->socket_host,
$this->socket_host, $this->socket_port,
$this->socket_port, socket_strerror(socket_last_error($this->connection))
socket_strerror(socket_last_error($this->connection))
)
); );
} }
socket_set_option($this->connection, SOL_TCP, TCP_NODELAY, 1); socket_set_option($this->connection, SOL_TCP, TCP_NODELAY, 1);
@ -266,11 +253,9 @@ class Connection
{ {
$this->connection = socket_create(AF_UNIX, SOCK_STREAM, 0); $this->connection = socket_create(AF_UNIX, SOCK_STREAM, 0);
if (! socket_connect($this->connection, $this->socket_path)) { if (! socket_connect($this->connection, $this->socket_path)) {
throw new \Exception( throw new IcingaException(
sprintf( 'Cannot connect to livestatus local socket "%s"',
'Cannot connect to livestatus local socket "%s"', $this->socket_path
$this->socket_path
)
); );
} }
} }

View File

@ -5,6 +5,7 @@
namespace Icinga\Protocol\Livestatus; namespace Icinga\Protocol\Livestatus;
use Icinga\Protocol\AbstractQuery; use Icinga\Protocol\AbstractQuery;
use Icinga\Exception\IcingaException;
class Query extends AbstractQuery class Query extends AbstractQuery
{ {
@ -86,12 +87,10 @@ class Query extends AbstractQuery
public function limit($count = null, $offset = null) public function limit($count = null, $offset = null)
{ {
if (! preg_match('~^\d+~', $count . $offset)) { if (! preg_match('~^\d+~', $count . $offset)) {
throw new Exception( throw new IcingaException(
sprintf( 'Got invalid limit: %s, %s',
'Got invalid limit: %s, %s', $count,
$count, $offset
$offset
)
); );
} }
$this->limit_count = (int) $count; $this->limit_count = (int) $count;
@ -122,11 +121,9 @@ class Query extends AbstractQuery
public function from($table, $columns = null) public function from($table, $columns = null)
{ {
if (! $this->connection->hasTable($table)) { if (! $this->connection->hasTable($table)) {
throw new Exception( throw new IcingaException(
sprintf( 'This livestatus connection does not provide "%s"',
'This livestatus connection does not provide "%s"', $table
$table
)
); );
} }
$this->table = $table; $this->table = $table;
@ -169,7 +166,7 @@ class Query extends AbstractQuery
public function __toString() public function __toString()
{ {
if ($this->table === null) { if ($this->table === null) {
throw new Exception('Table is required'); throw new IcingaException('Table is required');
} }
$default_headers = array( $default_headers = array(
'OutputFormat: json', 'OutputFormat: json',

View File

@ -4,6 +4,8 @@
namespace Icinga\Protocol\Nrpe; namespace Icinga\Protocol\Nrpe;
use Icinga\Exception\IcingaException;
class Connection class Connection
{ {
protected $host; protected $host;
@ -47,11 +49,10 @@ class Connection
// TODO: Check result checksum! // TODO: Check result checksum!
$result = fread($conn, 8192); $result = fread($conn, 8192);
if ($result === false) { if ($result === false) {
throw new \Exception('CHECK_NRPE: Error receiving data from daemon.'); throw new IcingaException('CHECK_NRPE: Error receiving data from daemon.');
} elseif (strlen($result) === 0) { } elseif (strlen($result) === 0) {
throw new \Exception( throw new IcingaException(
'CHECK_NRPE: Received 0 bytes from daemon.' 'CHECK_NRPE: Received 0 bytes from daemon. Check the remote server logs for error messages'
. ' Check the remote server logs for error messages'
); );
} }
// TODO: CHECK_NRPE: Receive underflow - only %d bytes received (%d expected) // TODO: CHECK_NRPE: Receive underflow - only %d bytes received (%d expected)
@ -80,7 +81,10 @@ class Connection
$ctx $ctx
); );
if (! $this->connection) { if (! $this->connection) {
throw new \Exception(sprintf('NRPE Connection failed: ' . $errstr)); throw new IcingaException(
'NRPE Connection failed: %s',
$errstr
);
} }
} }

View File

@ -9,6 +9,7 @@ use Icinga\Exception\ProgrammingError;
use Icinga\Data\SimpleQuery; use Icinga\Data\SimpleQuery;
use Icinga\Protocol\Statusdat\View\MonitoringObjectList; use Icinga\Protocol\Statusdat\View\MonitoringObjectList;
use Icinga\Protocol\Statusdat\Query\IQueryPart; use Icinga\Protocol\Statusdat\Query\IQueryPart;
use Icinga\Exception\IcingaException;
/** /**
* Base implementation for Statusdat queries. * Base implementation for Statusdat queries.
@ -163,7 +164,7 @@ class Query extends SimpleQuery
* @param array $columns An array of attributes to use (required for fetchPairs()) * @param array $columns An array of attributes to use (required for fetchPairs())
* *
* @return $this Fluent interface * @return $this Fluent interface
* @throws \Exception If the target is unknonw * @throws IcingaException If the target is unknonw
*/ */
public function from($table, array $attributes = null) public function from($table, array $attributes = null)
{ {
@ -173,7 +174,10 @@ class Query extends SimpleQuery
if (isset(self::$VALID_TARGETS[$table])) { if (isset(self::$VALID_TARGETS[$table])) {
$this->source = $table; $this->source = $table;
} else { } else {
throw new \Exception('Unknown from target for status.dat :' . $table); throw new IcingaException(
'Unknown from target for status.dat :%s',
$table
);
} }
return $this; return $this;
} }
@ -397,16 +401,15 @@ class Query extends SimpleQuery
/** /**
* Fetch the result as an associative array using the first column as the key and the second as the value * Fetch the result as an associative array using the first column as the key and the second as the value
* *
* @return array An associative array with the result * @return array An associative array with the result
* @throws \Exception If no attributes are defined * @throws IcingaException If no attributes are defined
*/ */
public function fetchPairs() public function fetchPairs()
{ {
$result = array(); $result = array();
if (count($this->getColumns()) < 2) { if (count($this->getColumns()) < 2) {
throw new Exception( throw new IcingaException(
'Status.dat "fetchPairs()" query expects at least' . 'Status.dat "fetchPairs()" query expects at least columns to be set in the query expression'
' columns to be set in the query expression'
); );
} }
$attributes = $this->getColumns(); $attributes = $this->getColumns();

View File

@ -4,6 +4,8 @@
namespace Icinga\Protocol\Statusdat\Query; namespace Icinga\Protocol\Statusdat\Query;
use Icinga\Exception\IcingaException;
class Expression implements IQueryPart class Expression implements IQueryPart
{ {
/** /**
@ -70,7 +72,7 @@ class Expression implements IQueryPart
/** /**
* @param $token * @param $token
* @throws \Exception * @throws IcingaException
*/ */
private function getOperatorType($token) private function getOperatorType($token)
{ {
@ -106,7 +108,11 @@ class Expression implements IQueryPart
$this->CB = "isNotIn"; $this->CB = "isNotIn";
break; break;
default: default:
throw new \Exception("Unknown operator $token in expression $this->expression !"); throw new IcingaException(
'Unknown operator %s in expression %s !',
$token,
$this->expression
);
} }
} }

View File

@ -4,6 +4,8 @@
namespace Icinga\Protocol\Statusdat\Query; namespace Icinga\Protocol\Statusdat\Query;
use Icinga\Exception\IcingaException;
/** /**
* Class Group * Class Group
* @package Icinga\Protocol\Statusdat\Query * @package Icinga\Protocol\Statusdat\Query
@ -130,7 +132,7 @@ class Group implements IQueryPart
} }
/** /**
* @throws \Exception * @throws IcingaException
*/ */
private function tokenize() private function tokenize()
{ {
@ -154,7 +156,10 @@ class Group implements IQueryPart
} }
if ($token === self::GROUP_END) { if ($token === self::GROUP_END) {
if ($subgroupCount < 1) { if ($subgroupCount < 1) {
throw new \Exception("Invalid Query: unexpected ')' at pos " . $this->parsePos); throw new IcingaException(
'Invalid Query: unexpected \')\' at pos %s',
$this->parsePos
);
} }
$subgroupCount--; $subgroupCount--;
/* /*
@ -192,7 +197,7 @@ class Group implements IQueryPart
$this->subExpressionLength = $this->parsePos - $this->subExpressionStart; $this->subExpressionLength = $this->parsePos - $this->subExpressionStart;
} }
if ($subgroupCount > 0) { if ($subgroupCount > 0) {
throw new \Exception("Unexpected end of query, are you missing a parenthesis?"); throw new IcingaException('Unexpected end of query, are you missing a parenthesis?');
} }
$this->startNewSubExpression(); $this->startNewSubExpression();

View File

@ -8,6 +8,7 @@ use Iterator;
use Countable; use Countable;
use ArrayAccess; use ArrayAccess;
use Exception; use Exception;
use Icinga\Exception\IcingaException;
/** /**
* Wrapper around an array of monitoring objects that can be enhanced with an optional * Wrapper around an array of monitoring objects that can be enhanced with an optional
@ -115,7 +116,7 @@ class MonitoringObjectList implements Iterator, Countable, ArrayAccess
public function __set($name, $value) public function __set($name, $value)
{ {
throw new Exception("Setting is currently not available for objects"); throw new IcingaException('Setting is currently not available for objects');
} }
public function offsetExists($offset) public function offsetExists($offset)

View File

@ -5,6 +5,7 @@
namespace Icinga\Util; namespace Icinga\Util;
use Exception; use Exception;
use Icinga\Exception\IcingaException;
/** /**
* Helper class to ease internationalization when using gettext * Helper class to ease internationalization when using gettext
@ -53,12 +54,16 @@ class Translator
* @param string $name The name of the domain to register * @param string $name The name of the domain to register
* @param string $directory The directory where message catalogs can be found * @param string $directory The directory where message catalogs can be found
* *
* @throws Exception In case the domain was not successfully registered * @throws IcingaException In case the domain was not successfully registered
*/ */
public static function registerDomain($name, $directory) public static function registerDomain($name, $directory)
{ {
if (bindtextdomain($name, $directory) === false) { if (bindtextdomain($name, $directory) === false) {
throw new Exception("Cannot register domain '$name' with path '$directory'"); throw new IcingaException(
'Cannot register domain \'%s\' with path \'%s\'',
$name,
$directory
);
} }
bind_textdomain_codeset($name, 'UTF-8'); bind_textdomain_codeset($name, 'UTF-8');
self::$knownDomains[$name] = $directory; self::$knownDomains[$name] = $directory;
@ -69,14 +74,17 @@ class Translator
* *
* @param string $localeName The name of the locale to use * @param string $localeName The name of the locale to use
* *
* @throws Exception In case the locale's name is invalid * @throws IcingaException In case the locale's name is invalid
*/ */
public static function setupLocale($localeName) public static function setupLocale($localeName)
{ {
if (setlocale(LC_ALL, $localeName . '.UTF-8') === false && setlocale(LC_ALL, $localeName) === false) { if (setlocale(LC_ALL, $localeName . '.UTF-8') === false && setlocale(LC_ALL, $localeName) === false) {
setlocale(LC_ALL, 'C'); // C == "use whatever is hardcoded" setlocale(LC_ALL, 'C'); // C == "use whatever is hardcoded"
if ($localeName !== self::DEFAULT_LOCALE) { if ($localeName !== self::DEFAULT_LOCALE) {
throw new Exception("Cannot set locale '$localeName' for category 'LC_ALL'"); throw new IcingaException(
'Cannot set locale \'%s\' for category \'LC_ALL\'',
$localeName
);
} }
} else { } else {
$locale = setlocale(LC_ALL, 0); $locale = setlocale(LC_ALL, 0);

View File

@ -8,6 +8,7 @@ use Exception;
use Icinga\Authentication\Manager as AuthManager; use Icinga\Authentication\Manager as AuthManager;
use Icinga\Application\Benchmark; use Icinga\Application\Benchmark;
use Icinga\Application\Config; use Icinga\Application\Config;
use Icinga\Exception\IcingaException;
use Icinga\Util\Translator; use Icinga\Util\Translator;
use Icinga\Web\Widget\Tabs; use Icinga\Web\Widget\Tabs;
use Icinga\Web\Window; use Icinga\Web\Window;
@ -177,7 +178,10 @@ class ActionController extends Zend_Controller_Action
{ {
if (! $this->Auth()->hasPermission($name)) { if (! $this->Auth()->hasPermission($name)) {
// TODO: Shall this be an Auth Exception? Or a 404? // TODO: Shall this be an Auth Exception? Or a 404?
throw new Exception(sprintf('Auth error, no permission for "%s"', $name)); throw new IcingaException(
'Auth error, no permission for "%s"',
$name
);
} }
} }
@ -381,7 +385,7 @@ class ActionController extends Zend_Controller_Action
if ($this->view->title) { if ($this->view->title) {
if (preg_match('~[\r\n]~', $this->view->title)) { if (preg_match('~[\r\n]~', $this->view->title)) {
// TODO: Innocent exception and error log for hack attempts // TODO: Innocent exception and error log for hack attempts
throw new Exception('No way, guy'); throw new IcingaException('No way, guy');
} }
$resp->setHeader( $resp->setHeader(
'X-Icinga-Title', 'X-Icinga-Title',

View File

@ -6,6 +6,7 @@ namespace Icinga\Web\Session;
use Exception; use Exception;
use ArrayIterator; use ArrayIterator;
use Icinga\Exception\IcingaException;
use IteratorAggregate; use IteratorAggregate;
/** /**
@ -76,7 +77,10 @@ class SessionNamespace implements IteratorAggregate
public function __get($key) public function __get($key)
{ {
if (!array_key_exists($key, $this->values)) { if (!array_key_exists($key, $this->values)) {
throw new Exception('Cannot access non-existent session value "' . $key . '"'); throw new IcingaException(
'Cannot access non-existent session value "%s"',
$key
);
} }
return $this->get($key); return $this->get($key);
@ -178,7 +182,7 @@ class SessionNamespace implements IteratorAggregate
public function write() public function write()
{ {
if (!$this->session) { if (!$this->session) {
throw new Exception('Cannot save, session not set'); throw new IcingaException('Cannot save, session not set');
} }
$this->session->write(); $this->session->write();

View File

@ -4,6 +4,7 @@
namespace Icinga\Web\Widget\Dashboard; namespace Icinga\Web\Widget\Dashboard;
use Icinga\Exception\IcingaException;
use Icinga\Util\Dimension; use Icinga\Util\Dimension;
use Icinga\Web\Form; use Icinga\Web\Form;
use Icinga\Web\Url; use Icinga\Web\Url;
@ -81,11 +82,9 @@ EOD;
} elseif ($url) { } elseif ($url) {
$this->url = Url::fromPath($url); $this->url = Url::fromPath($url);
} else { } else {
throw new Exception( throw new IcingaException(
sprintf( 'Cannot create dashboard component "%s" without valid URL',
'Cannot create dashboard component "%s" without valid URL', $title
$title
)
); );
} }
} }

View File

@ -25,6 +25,7 @@ use Icinga\Module\Monitoring\Form\Command\DelayNotificationForm;
use Icinga\Module\Monitoring\Form\Command\RescheduleNextCheckForm; use Icinga\Module\Monitoring\Form\Command\RescheduleNextCheckForm;
use Icinga\Module\Monitoring\Form\Command\ScheduleDowntimeForm; use Icinga\Module\Monitoring\Form\Command\ScheduleDowntimeForm;
use Icinga\Module\Monitoring\Form\Command\SubmitPassiveCheckResultForm; use Icinga\Module\Monitoring\Form\Command\SubmitPassiveCheckResultForm;
use Icinga\Exception\IcingaException;
/** /**
* Class Monitoring_CommandController * Class Monitoring_CommandController
@ -238,13 +239,16 @@ class Monitoring_CommandController extends Controller
$given = array_intersect_key($supported, $this->getRequest()->getParams()); $given = array_intersect_key($supported, $this->getRequest()->getParams());
if (empty($given)) { if (empty($given)) {
throw new \Exception('Missing parameter, supported: '.implode(', ', array_flip($supported))); throw new IcingaException(
'Missing parameter, supported: %s',
implode(', ', array_flip($supported))
);
} }
if (isset($given['host'])) { if (isset($given['host'])) {
$objects = $this->selectCommandTargets(!in_array("service", $supported)); $objects = $this->selectCommandTargets(!in_array("service", $supported));
if (empty($objects)) { if (empty($objects)) {
throw new \Exception("No objects found for your command"); throw new IcingaException('No objects found for your command');
} }
} }

View File

@ -4,6 +4,7 @@
namespace Icinga\Module\Monitoring\Backend\Ido\Query; namespace Icinga\Module\Monitoring\Backend\Ido\Query;
use Icinga\Exception\IcingaException;
use Icinga\Logger\Logger; use Icinga\Logger\Logger;
use Icinga\Data\Db\DbQuery; use Icinga\Data\Db\DbQuery;
use Icinga\Exception\ProgrammingError; use Icinga\Exception\ProgrammingError;
@ -272,7 +273,10 @@ abstract class IdoQuery extends DbQuery
$this->requireColumn($condition); $this->requireColumn($condition);
$col = $this->getMappedField($condition); $col = $this->getMappedField($condition);
if ($col === null) { if ($col === null) {
throw new \Exception("No such field: $condition"); throw new IcingaException(
'No such field: %s',
$condition
);
} }
return parent::where($col, $value); return parent::where($col, $value);
} }

View File

@ -7,6 +7,7 @@ namespace Icinga\Module\Monitoring\Timeline;
use DateTime; use DateTime;
use Exception; use Exception;
use ArrayIterator; use ArrayIterator;
use Icinga\Exception\IcingaException;
use IteratorAggregate; use IteratorAggregate;
use Icinga\Data\Filter\Filter; use Icinga\Data\Filter\Filter;
use Icinga\Web\Hook; use Icinga\Web\Hook;
@ -166,7 +167,10 @@ class TimeLine implements IteratorAggregate
$this->circleDiameter = floatval($matches[1]); $this->circleDiameter = floatval($matches[1]);
$this->diameterUnit = $matches[2]; $this->diameterUnit = $matches[2];
} else { } else {
throw new Exception('Width "' . $width . '" is not a valid width'); throw new IcingaException(
'Width "%s" is not a valid width',
$width
);
} }
} }
@ -184,10 +188,16 @@ class TimeLine implements IteratorAggregate
if ($matches[2] === $this->diameterUnit) { if ($matches[2] === $this->diameterUnit) {
$this->minCircleDiameter = floatval($matches[1]); $this->minCircleDiameter = floatval($matches[1]);
} else { } else {
throw new Exception('Unit needs to be in "' . $this->diameterUnit . '"'); throw new IcingaException(
'Unit needs to be in "%s"',
$this->diameterUnit
);
} }
} else { } else {
throw new Exception('Width "' . $width . '" is not a valid width'); throw new IcingaException(
'Width "%s" is not a valid width',
$width
);
} }
} }

View File

@ -6,6 +6,7 @@ namespace Icinga\Module\Translation\Cli;
use Exception; use Exception;
use Icinga\Cli\Command; use Icinga\Cli\Command;
use Icinga\Exception\IcingaException;
/** /**
* Base class for translation commands * Base class for translation commands
@ -24,7 +25,10 @@ class TranslationCommand extends Command
public function validateLocaleCode($code) public function validateLocaleCode($code)
{ {
if (! preg_match('@[a-z]{2}_[A-Z]{2}@', $code)) { if (! preg_match('@[a-z]{2}_[A-Z]{2}@', $code)) {
throw new Exception("Locale code '$code' is not valid. Expected format is: ll_CC"); throw new IcingaException(
'Locale code \'%s\' is not valid. Expected format is: ll_CC',
$code
);
} }
return $code; return $code;
@ -44,7 +48,10 @@ class TranslationCommand extends Command
$enabledModules = $this->app->getModuleManager()->listEnabledModules(); $enabledModules = $this->app->getModuleManager()->listEnabledModules();
if (!in_array($name, $enabledModules)) { if (!in_array($name, $enabledModules)) {
throw new Exception("Module with name '$name' not found or is not enabled"); throw new IcingaException(
'Module with name \'%s\' not found or is not enabled',
$name
);
} }
return $name; return $name;

View File

@ -5,6 +5,7 @@
namespace Icinga\Module\Translation\Util; namespace Icinga\Module\Translation\Util;
use Exception; use Exception;
use Icinga\Exception\IcingaException;
use Icinga\Util\File; use Icinga\Util\File;
use Icinga\Application\Modules\Manager; use Icinga\Application\Modules\Manager;
use Icinga\Application\ApplicationBootstrap; use Icinga\Application\ApplicationBootstrap;
@ -215,7 +216,10 @@ class GettextTranslationHelper
} else { } else {
if ((!is_dir(dirname($this->tablePath)) && !@mkdir(dirname($this->tablePath), 0755, true)) || if ((!is_dir(dirname($this->tablePath)) && !@mkdir(dirname($this->tablePath), 0755, true)) ||
!rename($this->templatePath, $this->tablePath)) { !rename($this->templatePath, $this->tablePath)) {
throw new Exception('Unable to create ' . $this->tablePath); throw new IcingaException(
'Unable to create %s',
$this->tablePath
);
} }
} }
$this->updateHeader($this->tablePath); $this->updateHeader($this->tablePath);
@ -364,7 +368,10 @@ class GettextTranslationHelper
{ {
$directoryHandle = opendir($directory); $directoryHandle = opendir($directory);
if (!$directoryHandle) { if (!$directoryHandle) {
throw new Exception('Unable to read files from ' . $directory); throw new IcingaException(
'Unable to read files from %s',
$directory
);
} }
$subdirs = array(); $subdirs = array();