wikimedia/mediawiki-extensions-Wikibase

View on GitHub
repo/rest-api/src/RouteHandlers/Middleware/UnexpectedErrorHandlerMiddleware.php

Summary

Maintainability
A
0 mins
Test Coverage
<?php declare( strict_types=1 );

namespace Wikibase\Repo\RestApi\RouteHandlers\Middleware;

use MediaWiki\Rest\Handler;
use MediaWiki\Rest\Reporter\ErrorReporter;
use MediaWiki\Rest\Response;
use Throwable;
use Wikibase\Repo\RestApi\Application\UseCases\UseCaseError;
use Wikibase\Repo\RestApi\RouteHandlers\ResponseFactory;

/**
 * @license GPL-2.0-or-later
 */
class UnexpectedErrorHandlerMiddleware implements Middleware {

    private ResponseFactory $responseFactory;
    private ErrorReporter $errorReporter;

    public function __construct(
        ResponseFactory $responseFactory,
        ErrorReporter $errorReporter
    ) {
        $this->responseFactory = $responseFactory;
        $this->errorReporter = $errorReporter;
    }

    public function run( Handler $routeHandler, callable $runNext ): Response {
        try {
            return $runNext();
        } catch ( Throwable $exception ) {
            $this->errorReporter->reportError( $exception, $routeHandler, $routeHandler->getRequest() );

            return $this->responseFactory->newErrorResponse(
                UseCaseError::UNEXPECTED_ERROR,
                'Unexpected error'
            );
        }
    }

}