1
0
Files
GongShangLian/app/Exceptions/ApiExceptions.php
2020-08-06 15:36:28 +08:00

53 lines
1.7 KiB
PHP

<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Validation\ValidationException;
use Response;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
class ApiExceptions
{
protected $request;
protected $message;
protected $code = 4000;
public function render($request, Exception $exception)
{
$this->request = $request;
$this->message = $exception->getMessage();
if ($exception instanceof TokenExpiredException || $exception instanceof UnauthorizedHttpException || $exception instanceof TokenInvalidException) {
$this->code = 4001;
} elseif ($exception instanceof MethodNotAllowedHttpException) {
$this->code = 4005;
$this->message = '[ ' . $request->method() . ' ] 请求方法不允许';
} elseif ($exception instanceof NotFoundHttpException) {
$this->code = 4004;
} elseif ($exception instanceof ValidationException) {
$this->code = 4017;
$this->message = array_shift($exception->errors())[0];
}
return Response::json($this->getError());
}
protected function getError()
{
return [
'status' => 'ERROR',
'error_code' => $this->code,
'message' => $this->message,
'api_uri' => $this->request->url(),
];
}
}