|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Pharaonic\Laravel\Jsonable\Exceptions; |
| 4 | + |
| 5 | +use Exception as GlobalException; |
| 6 | + |
| 7 | +class Exception extends GlobalException |
| 8 | +{ |
| 9 | + protected ?string $exCode = null; |
| 10 | + |
| 11 | + public function __construct(string $message = "", ?string $code = null, ?Throwable $previous = null) |
| 12 | + { |
| 13 | + parent::__construct($message, 0, $previous); |
| 14 | + $this->exCode = $code; |
| 15 | + } |
| 16 | + |
| 17 | + /** |
| 18 | + * Render the exception as an HTTP response. |
| 19 | + * |
| 20 | + * @param \Illuminate\Http\Request $request |
| 21 | + * @return \Illuminate\Http\Response |
| 22 | + */ |
| 23 | + public function render($request) |
| 24 | + { |
| 25 | + if ($request->wantsJson()) |
| 26 | + return $request->header('accept') == 'application/vnd.api+json' ? |
| 27 | + $this->renderJsonApi() : |
| 28 | + $this->renderJson(); |
| 29 | + |
| 30 | + if (!empty($this->exCode)) |
| 31 | + $this->message = $this->exCode . ' :: ' . $this->message; |
| 32 | + |
| 33 | + return; |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * Render the json response |
| 38 | + * |
| 39 | + * @return \Illuminate\Http\JsonResponse |
| 40 | + */ |
| 41 | + private function renderJson() |
| 42 | + { |
| 43 | + return response()->json([ |
| 44 | + 'success' => false, |
| 45 | + 'code' => $this->exCode ?? $this->getCode() ?? null, |
| 46 | + 'message' => $this->getMessage(), |
| 47 | + 'data' => (object) (app()->environment('local', 'staging') ? |
| 48 | + [ |
| 49 | + 'line' => $this->getLine(), |
| 50 | + 'file' => $this->getFile(), |
| 51 | + ] + (config('Pharaonic.jsonable.tracing', false) ? ['trace' => $this->getTrace()] : []) |
| 52 | + : [] |
| 53 | + ) |
| 54 | + ]); |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * Render the JSON:API response |
| 59 | + * |
| 60 | + * @return \Illuminate\Http\JsonResponse |
| 61 | + */ |
| 62 | + private function renderJsonApi() |
| 63 | + { |
| 64 | + return response()->json([ |
| 65 | + // 'success' => false, |
| 66 | + // 'code' => $this->exCode ?? $this->getCode() ?? null, |
| 67 | + // 'message' => $this->getMessage(), |
| 68 | + // 'data' => (object) (app()->environment('local', 'staging') ? |
| 69 | + // [ |
| 70 | + // 'line' => $this->getLine(), |
| 71 | + // 'file' => $this->getFile(), |
| 72 | + // ] + (config('Pharaonic.jsonable.tracing', false) ? ['trace' => $this->getTrace()] : []) |
| 73 | + // : [] |
| 74 | + // ) |
| 75 | + ]); |
| 76 | + } |
| 77 | +} |
0 commit comments