44
55use Exception ;
66use Utopia \Storage \Device ;
7+ use Utopia \Storage \Exception \NotFoundException ;
78use Utopia \Storage \Storage ;
89
910class S3 extends Device
@@ -284,7 +285,7 @@ public function transfer(string $path, string $destination, Device $device): boo
284285 try {
285286 $ response = $ this ->getInfo ($ path );
286287 } catch (\Throwable $ e ) {
287- throw new Exception ('File not found ' );
288+ throw new NotFoundException ('File not found ' );
288289 }
289290 $ size = (int ) ($ response ['content-length ' ] ?? 0 );
290291 $ contentType = $ response ['content-type ' ] ?? '' ;
@@ -903,7 +904,7 @@ protected function call(string $operation, string $method, string $uri, string $
903904 }
904905
905906 if ($ response ->code >= 400 ) {
906- throw new Exception ($ response ->body , $ response ->code );
907+ $ this -> parseAndThrowS3Error ($ response ->body , $ response ->code );
907908 }
908909
909910 // Parse body into XML
@@ -927,6 +928,35 @@ protected function call(string $operation, string $method, string $uri, string $
927928 }
928929 }
929930
931+ /**
932+ * Parse S3 XML error response and throw appropriate exception
933+ *
934+ * @param string $errorBody The error response body
935+ * @param int $statusCode The HTTP status code
936+ * @throws NotFoundException When the error is NoSuchKey
937+ * @throws Exception For other S3 errors
938+ */
939+ private function parseAndThrowS3Error (string $ errorBody , int $ statusCode ): void
940+ {
941+ if (str_starts_with ($ errorBody , '<?xml ' )) {
942+ try {
943+ $ xml = \simplexml_load_string ($ errorBody );
944+ $ errorCode = (string ) ($ xml ->Code ?? '' );
945+ $ errorMessage = (string ) ($ xml ->Message ?? '' );
946+
947+ if ($ errorCode === 'NoSuchKey ' ) {
948+ throw new NotFoundException ($ errorMessage ?: 'File not found ' , $ statusCode );
949+ }
950+ } catch (NotFoundException $ e ) {
951+ throw $ e ;
952+ } catch (\Throwable $ e ) {
953+ // If XML parsing fails, fall through to original error
954+ }
955+ }
956+
957+ throw new Exception ($ errorBody , $ statusCode );
958+ }
959+
930960 /**
931961 * Sort compare for meta headers
932962 *
0 commit comments