44
55namespace App \Http ;
66
7- use App \Exception \ApplicationException ;
87use Psr \Http \Message \ResponseInterface ;
98use Psr \Http \Message \ServerRequestInterface ;
109use Psr \Http \Server \MiddlewareInterface ;
1110use Psr \Http \Server \RequestHandlerInterface ;
11+ use Throwable ;
12+ use Yiisoft \ErrorHandler \Exception \UserException ;
1213use Yiisoft \Input \Http \InputValidationException ;
1314
15+ use function is_int ;
16+
1417final readonly class ExceptionMiddleware implements MiddlewareInterface
1518{
1619 public function __construct (
@@ -21,10 +24,17 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface
2124 {
2225 try {
2326 return $ handler ->handle ($ request );
24- } catch (ApplicationException $ e ) {
25- return $ this ->apiResponseFactory ->fail ($ e ->getMessage (), code: $ e ->getCode ());
26- } catch (InputValidationException $ e ) {
27- return $ this ->apiResponseFactory ->failValidation ($ e ->getResult ());
27+ } catch (InputValidationException $ exception ) {
28+ return $ this ->apiResponseFactory ->failValidation ($ exception ->getResult ());
29+ } catch (Throwable $ exception ) {
30+ if (UserException::isUserException ($ exception )) {
31+ $ code = $ exception ->getCode ();
32+ return $ this ->apiResponseFactory ->fail (
33+ $ exception ->getMessage (),
34+ code: is_int ($ code ) ? $ code : null ,
35+ );
36+ }
37+ throw $ exception ;
2838 }
2939 }
3040}
0 commit comments