3 namespace BookStack\Exceptions;
6 use Illuminate\Auth\AuthenticationException;
7 use Illuminate\Database\Eloquent\ModelNotFoundException;
8 use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
9 use Illuminate\Http\JsonResponse;
10 use Illuminate\Http\Request;
11 use Illuminate\Validation\ValidationException;
12 use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
15 class Handler extends ExceptionHandler
18 * A list of the exception types that are not reported.
20 * @var array<int, class-string<\Throwable>>
22 protected $dontReport = [
23 NotFoundException::class,
24 StoppedAuthenticationException::class,
28 * A list of the inputs that are never flashed to the session on validation exceptions.
30 * @var array<int, string>
32 protected $dontFlash = [
35 'password_confirmation',
39 * Report or log an exception.
41 * @param \Throwable $exception
47 public function report(Throwable $exception)
49 parent::report($exception);
53 * Render an exception into an HTTP response.
55 * @param \Illuminate\Http\Request $request
58 * @return \Illuminate\Http\Response
60 public function render($request, Throwable $e)
62 if ($this->isApiRequest($request)) {
63 return $this->renderApiException($e);
66 return parent::render($request, $e);
70 * Check if the given request is an API request.
72 protected function isApiRequest(Request $request): bool
74 return strpos($request->path(), 'api/') === 0;
78 * Render an exception when the API is in use.
80 protected function renderApiException(Throwable $e): JsonResponse
85 if ($e instanceof HttpExceptionInterface) {
86 $code = $e->getStatusCode();
87 $headers = $e->getHeaders();
90 if ($e instanceof ModelNotFoundException) {
96 'message' => $e->getMessage(),
100 if ($e instanceof ValidationException) {
101 $responseData['error']['message'] = 'The given data was invalid.';
102 $responseData['error']['validation'] = $e->errors();
106 $responseData['error']['code'] = $code;
108 return new JsonResponse($responseData, $code, $headers);
112 * Convert an authentication exception into an unauthenticated response.
114 * @param \Illuminate\Http\Request $request
115 * @param \Illuminate\Auth\AuthenticationException $exception
117 * @return \Illuminate\Http\Response
119 protected function unauthenticated($request, AuthenticationException $exception)
121 if ($request->expectsJson()) {
122 return response()->json(['error' => 'Unauthenticated.'], 401);
125 return redirect()->guest('login');
129 * Convert a validation exception into a JSON response.
131 * @param \Illuminate\Http\Request $request
132 * @param \Illuminate\Validation\ValidationException $exception
134 * @return \Illuminate\Http\JsonResponse
136 protected function invalidJson($request, ValidationException $exception)
138 return response()->json($exception->errors(), $exception->status);