this seems fine but you may want to have multiple catch to catch different exceptions that can be thrown..
Jan 4, 2019
4
Level 8
Catching errors with stripe?
Hi everybody, I'm playing with Stripe in laravel, I have my controller function where I create a customer and a source, now I was wondering how could I catch any error that occurs when trying to create customer/source, I would like to return back an error message telling the user what went wrong.
I added a try catch block but tbh I have never used try catch before, is it the best way to do this? How can I get error message?
This is my controller function:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Stripe\Stripe;
use Stripe\Charge;
use Stripe\Customer;
class StripeController extends Controller
{
public function createCustomerAndSource(Request $request){
try
{
Stripe::setApiKey(config('services.stripe.secret'));
$customer = Customer::create([
"email" => $request->input('email'),
"source" => $request->input('sourceId'),
]);
$user = new User;
$user->name = $request->input('name');
$user->password = bcrypt($request->input('password'));
$user->stripeCustomerId = $customer->id;
$user->save();
Auth::login($user);
return response()->json([
'message' => 'It worked!',
]);
}
catch(Exception $e)
{
return response()->json([
'message' => 'Oops, something went wrong!',
]);
}
}
Level 3
try{
Stripe::setApiKey(config('services.stripe.secret'));
$customer = Customer::create([
"email" => $request->input('email'),
"source" => $request->input('sourceId'),
]);
$user = new User;
$user->name = $request->input('name');
$user->password = bcrypt($request->input('password'));
$user->stripeCustomerId = $customer->id;
$user->save();
Auth::login($user);
return response()->json([
'message' => 'It worked!',
]);
}
catch (\Stripe\Error\ApiConnection $e) {
/* Network problem, perhaps try again. */
return response()->json([
'message' => 'Sorry, Network is having trouble. Please try again later.',
]);
} catch (\Stripe\Error\InvalidRequest $e) {
/* You screwed up in your programming. Shouldn't happen! */
return response()->json([
'message' => 'Sorry. One of our programmer forgot to drink their caffein.',
]);
} catch (\Stripe\Error\Api $e) {
/* Stripe's servers are down! */
return response()->json([
'message' => 'Sorry our payment processor is down at the moment.',
]);
} catch (\Stripe\Error\Card $e) {
/* Card was declined. */
return response()->json([
'message' => 'Your card is declined. Please try with a different card.',
]);
}
Please or to participate in this conversation.