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 = [
33 'password_confirmation',
37 * Report or log an exception.
39 * @param \Throwable $exception
45 public function report(Throwable $exception)
47 parent::report($exception);
51 * Render an exception into an HTTP response.
53 * @param \Illuminate\Http\Request $request
56 * @return \Illuminate\Http\Response
58 public function render($request, Throwable $e)
60 if ($this->isApiRequest($request)) {
61 return $this->renderApiException($e);
64 return parent::render($request, $e);
68 * Check if the given request is an API request.
70 protected function isApiRequest(Request $request): bool
72 return strpos($request->path(), 'api/') === 0;
76 * Render an exception when the API is in use.
78 protected function renderApiException(Exception $e): JsonResponse
80 $code = $e->getCode() === 0 ? 500 : $e->getCode();
82 if ($e instanceof HttpException) {
83 $code = $e->getStatusCode();
84 $headers = $e->getHeaders();
89 'message' => $e->getMessage(),
93 if ($e instanceof ValidationException) {
94 $responseData['error']['validation'] = $e->errors();
98 $responseData['error']['code'] = $code;
100 return new JsonResponse($responseData, $code, $headers);
104 * Convert an authentication exception into an unauthenticated response.
106 * @param \Illuminate\Http\Request $request
107 * @param \Illuminate\Auth\AuthenticationException $exception
109 * @return \Illuminate\Http\Response
111 protected function unauthenticated($request, AuthenticationException $exception)
113 if ($request->expectsJson()) {
114 return response()->json(['error' => 'Unauthenticated.'], 401);
117 return redirect()->guest('login');
121 * Convert a validation exception into a JSON response.
123 * @param \Illuminate\Http\Request $request
124 * @param \Illuminate\Validation\ValidationException $exception
126 * @return \Illuminate\Http\JsonResponse
128 protected function invalidJson($request, ValidationException $exception)
130 return response()->json($exception->errors(), $exception->status);