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;
13 class Handler extends ExceptionHandler
16 * A list of the exception types that are not reported.
20 protected $dontReport = [
21 NotFoundException::class,
25 * A list of the inputs that are never flashed for validation exceptions.
29 protected $dontFlash = [
31 'password_confirmation',
35 * Report or log an exception.
37 * @param Exception $exception
42 public function report(Exception $exception)
44 parent::report($exception);
48 * Render an exception into an HTTP response.
50 * @param \Illuminate\Http\Request $request
52 * @return \Illuminate\Http\Response
54 public function render($request, Exception $e)
56 if ($this->isApiRequest($request)) {
57 return $this->renderApiException($e);
60 return parent::render($request, $e);
64 * Check if the given request is an API request.
66 protected function isApiRequest(Request $request): bool
68 return strpos($request->path(), 'api/') === 0;
72 * Render an exception when the API is in use.
74 protected function renderApiException(Exception $e): JsonResponse
76 $code = $e->getCode() === 0 ? 500 : $e->getCode();
78 if ($e instanceof HttpException) {
79 $code = $e->getStatusCode();
80 $headers = $e->getHeaders();
85 'message' => $e->getMessage(),
89 if ($e instanceof ValidationException) {
90 $responseData['error']['validation'] = $e->errors();
94 $responseData['error']['code'] = $code;
95 return new JsonResponse($responseData, $code, $headers);
99 * Convert an authentication exception into an unauthenticated response.
101 * @param \Illuminate\Http\Request $request
102 * @param \Illuminate\Auth\AuthenticationException $exception
103 * @return \Illuminate\Http\Response
105 protected function unauthenticated($request, AuthenticationException $exception)
107 if ($request->expectsJson()) {
108 return response()->json(['error' => 'Unauthenticated.'], 401);
111 return redirect()->guest('login');
115 * Convert a validation exception into a JSON response.
117 * @param \Illuminate\Http\Request $request
118 * @param \Illuminate\Validation\ValidationException $exception
119 * @return \Illuminate\Http\JsonResponse
121 protected function invalidJson($request, ValidationException $exception)
123 return response()->json($exception->errors(), $exception->status);