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\HttpException;
15 class Handler extends ExceptionHandler
18 * A list of the exception types that are not reported.
22 protected $dontReport = [
23 NotFoundException::class,
27 * A list of the inputs that are never flashed for validation exceptions.
31 protected $dontFlash = [
34 'password_confirmation',
38 * Report or log an exception.
40 * @param \Throwable $exception
46 public function report(Throwable $exception)
48 parent::report($exception);
52 * Render an exception into an HTTP response.
54 * @param \Illuminate\Http\Request $request
57 * @return \Illuminate\Http\Response
59 public function render($request, Throwable $e)
61 if ($this->isApiRequest($request)) {
62 return $this->renderApiException($e);
65 return parent::render($request, $e);
69 * Check if the given request is an API request.
71 protected function isApiRequest(Request $request): bool
73 return strpos($request->path(), 'api/') === 0;
77 * Render an exception when the API is in use.
79 protected function renderApiException(Throwable $e): JsonResponse
84 if ($e instanceof HttpException) {
85 $code = $e->getStatusCode();
86 $headers = $e->getHeaders();
89 if ($e instanceof ModelNotFoundException) {
95 'message' => $e->getMessage(),
99 if ($e instanceof ValidationException) {
100 $responseData['error']['validation'] = $e->errors();
104 $responseData['error']['code'] = $code;
106 return new JsonResponse($responseData, $code, $headers);
110 * Convert an authentication exception into an unauthenticated response.
112 * @param \Illuminate\Http\Request $request
113 * @param \Illuminate\Auth\AuthenticationException $exception
115 * @return \Illuminate\Http\Response
117 protected function unauthenticated($request, AuthenticationException $exception)
119 if ($request->expectsJson()) {
120 return response()->json(['error' => 'Unauthenticated.'], 401);
123 return redirect()->guest('login');
127 * Convert a validation exception into a JSON response.
129 * @param \Illuminate\Http\Request $request
130 * @param \Illuminate\Validation\ValidationException $exception
132 * @return \Illuminate\Http\JsonResponse
134 protected function invalidJson($request, ValidationException $exception)
136 return response()->json($exception->errors(), $exception->status);