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
43 public function report(Exception $exception)
45 parent::report($exception);
49 * Render an exception into an HTTP response.
51 * @param \Illuminate\Http\Request $request
54 * @return \Illuminate\Http\Response
56 public function render($request, Exception $e)
58 if ($this->isApiRequest($request)) {
59 return $this->renderApiException($e);
62 return parent::render($request, $e);
66 * Check if the given request is an API request.
68 protected function isApiRequest(Request $request): bool
70 return strpos($request->path(), 'api/') === 0;
74 * Render an exception when the API is in use.
76 protected function renderApiException(Exception $e): JsonResponse
78 $code = $e->getCode() === 0 ? 500 : $e->getCode();
80 if ($e instanceof HttpException) {
81 $code = $e->getStatusCode();
82 $headers = $e->getHeaders();
87 'message' => $e->getMessage(),
91 if ($e instanceof ValidationException) {
92 $responseData['error']['validation'] = $e->errors();
96 $responseData['error']['code'] = $code;
98 return new JsonResponse($responseData, $code, $headers);
102 * Convert an authentication exception into an unauthenticated response.
104 * @param \Illuminate\Http\Request $request
105 * @param \Illuminate\Auth\AuthenticationException $exception
107 * @return \Illuminate\Http\Response
109 protected function unauthenticated($request, AuthenticationException $exception)
111 if ($request->expectsJson()) {
112 return response()->json(['error' => 'Unauthenticated.'], 401);
115 return redirect()->guest('login');
119 * Convert a validation exception into a JSON response.
121 * @param \Illuminate\Http\Request $request
122 * @param \Illuminate\Validation\ValidationException $exception
124 * @return \Illuminate\Http\JsonResponse
126 protected function invalidJson($request, ValidationException $exception)
128 return response()->json($exception->errors(), $exception->status);