]> BookStack Code Mirror - bookstack/blob - app/Exceptions/Handler.php
Merge branch 'fix/oidc-logout' into development
[bookstack] / app / Exceptions / Handler.php
1 <?php
2
3 namespace BookStack\Exceptions;
4
5 use Exception;
6 use Illuminate\Auth\AuthenticationException;
7 use Illuminate\Database\Eloquent\ModelNotFoundException;
8 use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
9 use Illuminate\Http\Exceptions\PostTooLargeException;
10 use Illuminate\Http\JsonResponse;
11 use Illuminate\Http\Request;
12 use Illuminate\Validation\ValidationException;
13 use Symfony\Component\ErrorHandler\Error\FatalError;
14 use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
15 use Throwable;
16
17 class Handler extends ExceptionHandler
18 {
19     /**
20      * A list of the exception types that are not reported.
21      *
22      * @var array<int, class-string<\Throwable>>
23      */
24     protected $dontReport = [
25         NotFoundException::class,
26         StoppedAuthenticationException::class,
27     ];
28
29     /**
30      * A list of the inputs that are never flashed to the session on validation exceptions.
31      *
32      * @var array<int, string>
33      */
34     protected $dontFlash = [
35         'current_password',
36         'password',
37         'password_confirmation',
38     ];
39
40     /**
41      * A function to run upon out of memory.
42      * If it returns a response, that will be provided back to the request
43      * upon an out of memory event.
44      *
45      * @var ?callable<?\Illuminate\Http\Response>
46      */
47     protected $onOutOfMemory = null;
48
49     /**
50      * Report or log an exception.
51      *
52      * @param \Throwable $exception
53      *
54      * @throws \Throwable
55      *
56      * @return void
57      */
58     public function report(Throwable $exception)
59     {
60         parent::report($exception);
61     }
62
63     /**
64      * Render an exception into an HTTP response.
65      *
66      * @param \Illuminate\Http\Request $request
67      * @param Exception                $e
68      *
69      * @return \Illuminate\Http\Response
70      */
71     public function render($request, Throwable $e)
72     {
73         if ($e instanceof FatalError && str_contains($e->getMessage(), 'bytes exhausted (tried to allocate') && $this->onOutOfMemory) {
74             $response = call_user_func($this->onOutOfMemory);
75             if ($response) {
76                 return $response;
77             }
78         }
79
80         if ($e instanceof PostTooLargeException) {
81             $e = new NotifyException(trans('errors.server_post_limit'), '/', 413);
82         }
83
84         if ($this->isApiRequest($request)) {
85             return $this->renderApiException($e);
86         }
87
88         return parent::render($request, $e);
89     }
90
91     /**
92      * Provide a function to be called when an out of memory event occurs.
93      * If the callable returns a response, this response will be returned
94      * to the request upon error.
95      */
96     public function prepareForOutOfMemory(callable $onOutOfMemory)
97     {
98         $this->onOutOfMemory = $onOutOfMemory;
99     }
100
101     /**
102      * Forget the current out of memory handler, if existing.
103      */
104     public function forgetOutOfMemoryHandler()
105     {
106         $this->onOutOfMemory = null;
107     }
108
109     /**
110      * Check if the given request is an API request.
111      */
112     protected function isApiRequest(Request $request): bool
113     {
114         return str_starts_with($request->path(), 'api/');
115     }
116
117     /**
118      * Render an exception when the API is in use.
119      */
120     protected function renderApiException(Throwable $e): JsonResponse
121     {
122         $code = 500;
123         $headers = [];
124
125         if ($e instanceof HttpExceptionInterface) {
126             $code = $e->getStatusCode();
127             $headers = $e->getHeaders();
128         }
129
130         if ($e instanceof ModelNotFoundException) {
131             $code = 404;
132         }
133
134         $responseData = [
135             'error' => [
136                 'message' => $e->getMessage(),
137             ],
138         ];
139
140         if ($e instanceof ValidationException) {
141             $responseData['error']['message'] = 'The given data was invalid.';
142             $responseData['error']['validation'] = $e->errors();
143             $code = $e->status;
144         }
145
146         $responseData['error']['code'] = $code;
147
148         return new JsonResponse($responseData, $code, $headers);
149     }
150
151     /**
152      * Convert an authentication exception into an unauthenticated response.
153      *
154      * @param \Illuminate\Http\Request                 $request
155      * @param \Illuminate\Auth\AuthenticationException $exception
156      *
157      * @return \Illuminate\Http\Response
158      */
159     protected function unauthenticated($request, AuthenticationException $exception)
160     {
161         if ($request->expectsJson()) {
162             return response()->json(['error' => 'Unauthenticated.'], 401);
163         }
164
165         return redirect()->guest('login');
166     }
167
168     /**
169      * Convert a validation exception into a JSON response.
170      *
171      * @param \Illuminate\Http\Request                   $request
172      * @param \Illuminate\Validation\ValidationException $exception
173      *
174      * @return \Illuminate\Http\JsonResponse
175      */
176     protected function invalidJson($request, ValidationException $exception)
177     {
178         return response()->json($exception->errors(), $exception->status);
179     }
180 }