|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace georgique\yii2\jsonrpc; |
| 4 | + |
| 5 | +use Yii; |
| 6 | +use yii\base\UserException; |
| 7 | +use yii\web\Response; |
| 8 | + |
| 9 | +/** |
| 10 | + * Class ErrorHandler |
| 11 | + * This class is supposed to catch any unhandled errors and format them into JSON-RPC response. |
| 12 | + * @autho George Shestayev [email protected] |
| 13 | + * @package georgique\yii2\jsonrpc |
| 14 | + */ |
| 15 | +class ErrorHandler extends \yii\base\ErrorHandler |
| 16 | +{ |
| 17 | + |
| 18 | + /** |
| 19 | + * Renders the exception. |
| 20 | + * @param \Exception|\Error $exception the exception to be rendered. |
| 21 | + */ |
| 22 | + protected function renderException($exception) |
| 23 | + { |
| 24 | + if (Yii::$app->has('response')) { |
| 25 | + $response = Yii::$app->getResponse(); |
| 26 | + // reset parameters of response to avoid interference with partially created response data |
| 27 | + // in case the error occurred while sending the response. |
| 28 | + $response->isSent = false; |
| 29 | + $response->stream = null; |
| 30 | + $response->data = null; |
| 31 | + $response->content = null; |
| 32 | + } else { |
| 33 | + $response = new Response(); |
| 34 | + } |
| 35 | + |
| 36 | + $response->setStatusCode(200); |
| 37 | + $response->data = $this->convertExceptionToArray($exception); |
| 38 | + $response->send(); |
| 39 | + } |
| 40 | + |
| 41 | + /** |
| 42 | + * Converts an exception into an array. |
| 43 | + * @param \Exception|\Error $exception the exception being converted |
| 44 | + * @return array the array representation of the exception. |
| 45 | + */ |
| 46 | + protected function convertExceptionToArray($exception) |
| 47 | + { |
| 48 | + if (!YII_DEBUG && !$exception instanceof Exception) { |
| 49 | + $exception = new Exception('Internal error', JSON_RPC_ERROR_INTERNAL); |
| 50 | + } |
| 51 | + |
| 52 | + $errorArray = [ |
| 53 | + 'code' => $exception->getCode(), |
| 54 | + 'message' => $exception->getMessage(), |
| 55 | + 'data' => [] |
| 56 | + ]; |
| 57 | + if (YII_DEBUG) { |
| 58 | + $errorArray['data']['type'] = get_class($exception); |
| 59 | + if (!$exception instanceof UserException) { |
| 60 | + $errorArray['data']['file'] = $exception->getFile(); |
| 61 | + $errorArray['data']['line'] = $exception->getLine(); |
| 62 | + $errorArray['data']['stack-trace'] = explode("\n", $exception->getTraceAsString()); |
| 63 | + if ($exception instanceof \yii\db\Exception) { |
| 64 | + $errorArray['data']['error-info'] = $exception->errorInfo; |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + if (($prev = $exception->getPrevious()) !== null) { |
| 69 | + $errorArray['data']['previous'] = $this->convertExceptionToArray($prev); |
| 70 | + } |
| 71 | + |
| 72 | + return [ |
| 73 | + 'jsonrpc' => '2.0', |
| 74 | + 'error' => $errorArray, |
| 75 | + 'id' => ($exception instanceof Exception) ? $exception->id : null, |
| 76 | + ]; |
| 77 | + } |
| 78 | + |
| 79 | +} |
0 commit comments