ExceptionMiddleware::process()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 3
nop 2
dl 0
loc 10
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Http;
6
7
use App\Exception\ApplicationException;
8
use Psr\Http\Message\ResponseInterface;
9
use Psr\Http\Message\ServerRequestInterface;
10
use Psr\Http\Server\MiddlewareInterface;
11
use Psr\Http\Server\RequestHandlerInterface;
12
use Yiisoft\DataResponse\DataResponseFactoryInterface;
13
use Yiisoft\Http\Status;
14
use Yiisoft\Input\Http\InputValidationException;
15
16
final class ExceptionMiddleware implements MiddlewareInterface
17
{
18
    public function __construct(private DataResponseFactoryInterface $dataResponseFactory)
19
    {
20
    }
21
22
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
23
    {
24
        try {
25
            return $handler->handle($request);
26
        } catch (ApplicationException $e) {
27
            return $this->dataResponseFactory->createResponse($e->getMessage(), $e->getCode());
28
        } catch (InputValidationException $e) {
29
            return $this->dataResponseFactory->createResponse(
30
                $e->getResult()->getErrorMessages()[0],
31
                Status::BAD_REQUEST
32
            );
33
        }
34
    }
35
}
36