summaryrefslogtreecommitdiff
path: root/vendor/ruflin/elastica/lib/Elastica/Exception/ElasticsearchException.php
blob: 0f7509f91a4b691633e24268182a0ab23f299d71 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<?php

namespace Elastica\Exception;

/**
 * Elasticsearch exception
 *
 * @category Xodoa
 * @package Elastica
 * @author Ian Babrou <ibobrik@gmail.com>
 */
class ElasticsearchException extends \Exception
{

    const REMOTE_TRANSPORT_EXCEPTION = 'RemoteTransportException';

    /**
     * Elasticsearch exception name
     *
     * @var string|null
     */
    private $_exception;

    /**
     * Whether exception was local to server node or remote
     *
     * @var bool
     */
    private $_isRemote = false;

    /**
     * Constructs elasticsearch exception
     *
     * @param int $code Error code
     * @param string $error Error message from elasticsearch
     */
    public function __construct($code, $error)
    {
        $this->_parseError($error);
        parent::__construct($error, $code);
    }

    /**
     * Parse error message from elasticsearch
     *
     * @param string $error Error message
     */
    protected function _parseError($error)
    {
        $errors = explode(']; nested: ', $error);

        if (count($errors) == 1) {
            $this->_exception = $this->_extractException($errors[0]);
        } else {
            if ($this->_extractException($errors[0]) == self::REMOTE_TRANSPORT_EXCEPTION) {
                $this->_isRemote = true;
                $this->_exception = $this->_extractException($errors[1]);
            } else {
                $this->_exception = $this->_extractException($errors[0]);
            }
        }
    }

    /**
     * Extract exception name from error response
     *
     * @param string $error
     * @return null|string
     */
    protected function _extractException($error)
    {
        if (preg_match('/^(\w+)\[.*\]/', $error, $matches)) {
            return $matches[1];
        } else {
            return null;
        }
    }

    /**
     * Returns elasticsearch exception name
     *
     * @return string|null
     */
    public function getExceptionName()
    {
        return $this->_exception;
    }

    /**
     * Returns whether exception was local to server node or remote
     *
     * @return bool
     */
    public function isRemoteTransportException()
    {
        return $this->_isRemote;
    }

}