Skip to content

Commit

Permalink
Custom method ModbusException::_toString()
Browse files Browse the repository at this point in the history
  • Loading branch information
alphp committed Oct 14, 2021
1 parent 66d5ee5 commit 3acd2fc
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 7 deletions.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "fawno/modbus",
"version": "0.1.3",
"version": "0.1.4",
"description": "Modbus RTU serial protocol in PHP",
"keywords": ["Modbus RTU", "DDS238"],
"license": "MIT",
Expand Down
34 changes: 28 additions & 6 deletions src/ModbusException.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,14 @@ class ModbusException extends Exception {
0x0B => 'Gateway target device failed to respond',
];

protected $_defaultMessage = '';
protected $_defaultCode = 0x00;
private $previous = null;
protected $request = null;
protected $response = null;

public function __construct (string $message = null, int $code = 0, string $request = null, string $response = null, Throwable $previous = null) {
$message = $message ?: $this->_defaultMessage;
$code = $code ?: $this->_defaultCode;
$this->request = bin2hex($request);
$this->response = bin2hex($response);
$this->previous = !is_null($previous) ? $previous : null;
$this->request = !is_null($request) ? bin2hex($request) : null;
$this->response = !is_null($response) ? bin2hex($response) : null;

if (empty($message) and $code != 0) {
$message = empty(self::EXCEPTION_CODES[$code]) ? self::EXCEPTION_CODES[0x00] : self::EXCEPTION_CODES[$code];
Expand All @@ -43,4 +41,28 @@ public function getRequest () {
public function getResponse () {
return $this->response;
}

public function __toString () {
$output = '';

if ($this->previous) {
$output .= $this->previous . "\n";
$output .= "\n" . 'Next ';
}

$output .= sprintf('%s: %s in %s:%s', get_class($this), $this->message, $this->file, $this->line) . "\n";

if ($this->request !== null) {
$output .= 'Request: "' . $this->request . '"' . "\n";
}

if ($this->response !== null) {
$output .= 'Response: "' . $this->response . '"' . "\n";
}

$output .= 'Stack trace:' . "\n";
$output .= $this->getTraceAsString();

return $output;
}
}

0 comments on commit 3acd2fc

Please sign in to comment.