Skip to content

Commit a83f9ca

Browse files
committed
feat(trait): ✨ 新增422與401狀況的builder
1 parent 7d929bf commit a83f9ca

File tree

1 file changed

+38
-6
lines changed

1 file changed

+38
-6
lines changed

src/Traits/ApiResponse.php

Lines changed: 38 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use Hankz\LaravelPlusApi\Classes\ApiResponseBuilder;
66
use Illuminate\Http\JsonResponse;
7+
use Illuminate\Validation\ValidationException;
78

89
trait ApiResponse
910
{
@@ -37,21 +38,52 @@ public static function success(
3738
* Builds error Response object. Supports optional arguments passed to Lang::get() if associated error
3839
* message uses placeholders as well as return data payload.
3940
*
40-
* @param string $apiCode your API code to be returned with the response object
41-
* @param string|null $message error message
42-
* @param int|null $httpCode HTTP code to be used for HttpResponse sent or @null
43-
* for default DEFAULT_HTTP_CODE_ERROR
44-
* @param int|null $headers Http Header
41+
* @param string $apiCode your API code to be returned with the response object
42+
* @param string|null $message error message
43+
* @param int|null $httpCode HTTP code to be used for HttpResponse sent or @null
44+
* for default DEFAULT_HTTP_CODE_ERROR
45+
* @param object|array|null $data array of primitives and supported objects to be returned in 'data' node
46+
* @param int|null $headers Http Header
4547
*/
4648
public static function error(
4749
string $apiCode,
48-
string $message = null,
4950
int $httpCode = null,
51+
string $message = null,
52+
$data = null,
5053
array $headers = null
5154
): JsonResponse {
5255
return ApiResponseBuilder::asError($apiCode)
5356
->withMessage($message)
5457
->withHttpCode($httpCode)
58+
->withData($data)
59+
->withHttpHeaders($headers)
60+
->build();
61+
}
62+
63+
/**
64+
* return validation error response.
65+
*/
66+
public static function validationError(ValidationException $e): JsonResponse
67+
{
68+
return ApiResponseBuilder::asError(config('plus-api.default_response.validation_fail.api_code'))
69+
->withErrors($e->errors())
70+
->withHttpCode($e->status)
71+
->build();
72+
}
73+
74+
public static function exceptionError(
75+
array $debug_data = null,
76+
string $apiCode = null,
77+
int $httpCode,
78+
string $message = null,
79+
array $headers = []
80+
): JsonResponse {
81+
$apiCode = $apiCode ?? config('plus-api.default_response.error.api_code');
82+
83+
return ApiResponseBuilder::asError($apiCode)
84+
->withDebugData($debug_data)
85+
->withHttpCode($httpCode)
86+
->withMessage($message)
5587
->withHttpHeaders($headers)
5688
->build();
5789
}

0 commit comments

Comments
 (0)