Skip to content

Commit 84e07d8

Browse files
committed
feat(exception): ✨ 新增基礎API Exception
1 parent 639a1fb commit 84e07d8

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

src/Exceptions/ApiException.php

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
<?php
2+
3+
namespace Hankz\LaravelPlusApi\Exceptions;
4+
5+
use Exception;
6+
use Hankz\LaravelPlusApi\Traits\ApiResponse;
7+
use Illuminate\Http\JsonResponse;
8+
use Illuminate\Http\Request;
9+
use Illuminate\Http\Response;
10+
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
11+
12+
abstract class ApiException extends Exception implements HttpExceptionInterface
13+
{
14+
use ApiResponse;
15+
16+
public const API_CODE = Response::HTTP_INTERNAL_SERVER_ERROR;
17+
18+
public const HTTP_CODE = Response::HTTP_INTERNAL_SERVER_ERROR;
19+
20+
/**
21+
* message.
22+
*
23+
* @var string
24+
*/
25+
protected $message;
26+
27+
/**
28+
* data.
29+
*
30+
* @var object|array|null data
31+
*/
32+
protected $data;
33+
34+
public function __construct(string $message = null, $data = null)
35+
{
36+
parent::__construct($message);
37+
38+
if (!is_null($message)) {
39+
$this->message = $message;
40+
}
41+
42+
if (!is_null($data)) {
43+
$this->data = $data;
44+
}
45+
}
46+
47+
/**
48+
* Report the exception.
49+
*/
50+
public function report(): bool
51+
{
52+
return true;
53+
}
54+
55+
/**
56+
* Render the exception into an HTTP response.
57+
*/
58+
public function render(Request $request): JsonResponse
59+
{
60+
return $this->error(
61+
static::API_CODE,
62+
static::HTTP_CODE,
63+
$this->message,
64+
$this->data
65+
);
66+
}
67+
}

0 commit comments

Comments
 (0)