1
votes

I'm using Stripe API, and the following line of code checks for a customer :

  $StripeCustomer = \Stripe\Customer::retrieve($cust_id);

If the customer ID is not found / doesn't exist as error is returned. At that point I would like to simply create a customer ID. But how do I catch and assess the error? There are various answers on SO for catching card errors, but they do not work the some as this GET request.

Laravels error handler does return the error. It looks like this :

in ApiRequestor.php line 181 at ApiRequestor::_specificAPIError('{ "error": { "code": "resource_missing", "doc_url": "https://stripe.com/docs/error-codes/resource-missing", "message": "No such customer: cus_CHDZD223OmY75y", "param": "id", "type": "invalid_request_error" } } ', '404', array('Server' => 'nginx', 'Date' => 'Mon, 13 Aug 2018 11:55:49 GMT', 'Content-Type' => 'application/json', 'Content-Length' => '234', 'Connection' => 'keep-alive', 'Access-Control-Allow-Credentials' => 'true', 'Access-Control-Allow-Methods' => 'GET, POST, HEAD, OPTIONS, DELETE', 'Access-Control-Allow-Origin' => '*', 'Access-Control-Expose-Headers' => 'Request-Id, Stripe-Manage-Version, X-Stripe-External-Auth-Required, X-Stripe-Privileged-Session-Required', 'Access-Control-Max-Age' => '300', 'Cache-Control' => 'no-cache, no-store', 'Request-Id' => 'req_0iY8NIWwT0tAqr', 'Stripe-Version' => '2018-07-27', 'Strict-Transport-Security' => 'max-age=31556926; includeSubDomains; preload'), array('error' => array('code' => 'resource_missing', 'doc_url' => 'https://stripe.com/docs/error-codes/resource-missing', 'message' => 'No such customer: cus_CHDZD223OmY75y', 'param' => 'id', 'type' => 'invalid_request_error')), array('code' => 'resource_missing', 'doc_url' => 'https://stripe.com/docs/error-codes/resource-missing', 'message' => 'No such customer: cus_CHDZD223OmY75y', 'param' => 'id', 'type' => 'invalid_request_error')) in ApiRequestor.php line 144

BUT I need to catch the error and check it. Any help appreciated.

tried so far

I have tried variations of the following try/catch :

try{
        $StripeCustomer = \Stripe\Customer::retrieve($cust_id);
   } catch (Exception $e){
      return "no customer found";
   }
1

1 Answers

2
votes

Your code looks generally correct, you should indeed use a try/catch block around the retrieve call. I would recommend looking at the response code returned from Stripe to determine if the exact error indicates that the customer does not exist, or if it is another type of error. Here's an example:

try{
  $customer = \Stripe\Customer::retrieve("cus_xxx");
}catch(\Stripe\Error\InvalidRequest $e){
  $body = $e->getJsonBody();
  $err  = $body['error'];
  if($err['code'] == "resource_missing"){
    print("customer does not exist!");
  }
}

You can read some more about handling Stripe errors in the docs.