Skyro682
Skyro682

Reputation: 190

How to fix 404 error when users haven't photo?

I use laravel and microsoft-graph api.

I need to get my users's photo but some haven't one and for them the api return a 404 error who bloc my page. what I wan't is to put a default profile photo for users who haven't one but i don't know how to pass the 404 error.

there is what my code do :

$photoLink = '/users\/' . $value['email'] . '/photos/240x240';
$photo = $graph->createRequest('GET', $photoLink . '/$value')->execute();
$photo = $photo->getRawBody();
$meta = $graph->createRequest("GET", $photoLink)->execute();
$meta = $meta->getBody();
echo '<img src="data:'.$meta["@odata.mediaContentType"].';base64,'.base64_encode($photo).'" />';

the error code : GuzzleHttp\Exception\ClientException thrown with message "Client error: GET https://graph.microsoft.com/v1.0/users/[email protected]/photos/240x240/$value resulted in a 404 Not Found response: { "error": { "code": "ErrorItemNotFound", "message": "The photo wasn't found.", "innerError": { (truncated...) "

Upvotes: 0

Views: 1216

Answers (1)

oktapodia
oktapodia

Reputation: 1758

I am not familiar with this api but it looks like you are trying to achieve that.

I can see from the microsoft graphql test that they are throwing a GraphException when getting back a 404 error.

The following should solves your issue:

use GuzzleHttp\Exception\ClientException;

try {   
    $photoLink = '/users\/' . $value['email'] . '/photos/240x240';
    $photo = $graph->createRequest('GET', $photoLink . '/$value')->execute();
    $photo = $photo->getRawBody();
    $meta = $graph->createRequest("GET", $photoLink)->execute();
    $meta = $meta->getBody();
    echo '<img src="data:'.$meta["@odata.mediaContentType"].';base64,'.base64_encode($photo).'" />';
} catch (ClientException $e) {
    if ($e->getStatusCode() === '404') {
        echo '<img src="MYDEFAULTIMAGEURL" />';
    }
}

EDIT: Code updated

Upvotes: 2

Related Questions