|
4 | 4 |
|
5 | 5 | use Hankz\LaravelPlusApi\Classes\ApiResponseBuilder; |
6 | 6 | use Illuminate\Http\JsonResponse; |
| 7 | +use Illuminate\Validation\ValidationException; |
7 | 8 |
|
8 | 9 | trait ApiResponse |
9 | 10 | { |
@@ -37,21 +38,52 @@ public static function success( |
37 | 38 | * Builds error Response object. Supports optional arguments passed to Lang::get() if associated error |
38 | 39 | * message uses placeholders as well as return data payload. |
39 | 40 | * |
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 |
45 | 47 | */ |
46 | 48 | public static function error( |
47 | 49 | string $apiCode, |
48 | | - string $message = null, |
49 | 50 | int $httpCode = null, |
| 51 | + string $message = null, |
| 52 | + $data = null, |
50 | 53 | array $headers = null |
51 | 54 | ): JsonResponse { |
52 | 55 | return ApiResponseBuilder::asError($apiCode) |
53 | 56 | ->withMessage($message) |
54 | 57 | ->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) |
55 | 87 | ->withHttpHeaders($headers) |
56 | 88 | ->build(); |
57 | 89 | } |
|
0 commit comments