aboutsummaryrefslogtreecommitdiffstats
path: root/apps/federation/lib/Middleware/AddServerMiddleware.php
blob: 8868e5c920709262c655d2b4a95d785131eebe79 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php

/**
 * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
 * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
 * SPDX-License-Identifier: AGPL-3.0-only
 */
namespace OCA\Federation\Middleware;

use OCA\Federation\Controller\SettingsController;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\JSONResponse;
use OCP\AppFramework\Middleware;
use OCP\HintException;
use OCP\IL10N;
use Psr\Log\LoggerInterface;

class AddServerMiddleware extends Middleware {
	protected string $appName;
	protected IL10N $l;
	protected LoggerInterface $logger;

	public function __construct(string $appName, IL10N $l, LoggerInterface $logger) {
		$this->appName = $appName;
		$this->l = $l;
		$this->logger = $logger;
	}

	/**
	 * Log error message and return a response which can be displayed to the user
	 *
	 * @param Controller $controller
	 * @param string $methodName
	 * @param \Exception $exception
	 * @return JSONResponse
	 * @throws \Exception
	 */
	public function afterException($controller, $methodName, \Exception $exception) {
		if (($controller instanceof SettingsController) === false) {
			throw $exception;
		}
		$this->logger->error($exception->getMessage(), [
			'app' => $this->appName,
			'exception' => $exception,
		]);
		if ($exception instanceof HintException) {
			$message = $exception->getHint();
		} else {
			$message = $exception->getMessage();
		}

		return new JSONResponse(
			['message' => $message],
			Http::STATUS_BAD_REQUEST
		);
	}
}