3 namespace BookStack\Exceptions;
6 use Illuminate\Auth\AuthenticationException;
7 use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
8 use Illuminate\Http\JsonResponse;
9 use Illuminate\Http\Request;
10 use Illuminate\Validation\ValidationException;
11 use Symfony\Component\HttpKernel\Exception\HttpException;
14 class Handler extends ExceptionHandler
17 * A list of the exception types that are not reported.
21 protected $dontReport = [
22 NotFoundException::class,
26 * A list of the inputs that are never flashed for validation exceptions.
30 protected $dontFlash = [
32 'password_confirmation',
36 * Report or log an exception.
38 * @param \Throwable $exception
44 public function report(Throwable $exception)
46 parent::report($exception);
50 * Render an exception into an HTTP response.
52 * @param \Illuminate\Http\Request $request
55 * @return \Illuminate\Http\Response
57 public function render($request, Throwable $e)
59 if ($this->isApiRequest($request)) {
60 return $this->renderApiException($e);
63 return parent::render($request, $e);
67 * Check if the given request is an API request.
69 protected function isApiRequest(Request $request): bool
71 return strpos($request->path(), 'api/') === 0;
75 * Render an exception when the API is in use.
77 protected function renderApiException(Exception $e): JsonResponse
79 $code = $e->getCode() === 0 ? 500 : $e->getCode();
81 if ($e instanceof HttpException) {
82 $code = $e->getStatusCode();
83 $headers = $e->getHeaders();
88 'message' => $e->getMessage(),
92 if ($e instanceof ValidationException) {
93 $responseData['error']['validation'] = $e->errors();
97 $responseData['error']['code'] = $code;
99 return new JsonResponse($responseData, $code, $headers);
103 * Convert an authentication exception into an unauthenticated response.
105 * @param \Illuminate\Http\Request $request
106 * @param \Illuminate\Auth\AuthenticationException $exception
108 * @return \Illuminate\Http\Response
110 protected function unauthenticated($request, AuthenticationException $exception)
112 if ($request->expectsJson()) {
113 return response()->json(['error' => 'Unauthenticated.'], 401);
116 return redirect()->guest('login');
120 * Convert a validation exception into a JSON response.
122 * @param \Illuminate\Http\Request $request
123 * @param \Illuminate\Validation\ValidationException $exception
125 * @return \Illuminate\Http\JsonResponse
127 protected function invalidJson($request, ValidationException $exception)
129 return response()->json($exception->errors(), $exception->status);