want to set exception for twilio - php

i am sending otp using twilio,laravel, message is working now, but i want to set exception for if message is not delivered etc i have tried like
public function send_otp()
{
try {
$account_sid = env('TWILIO_ACCOUNT_SID');
$auth_token = env('TWILIO_AUTH_TOKEN');
$number=Auth::user()->user_phone;
$client = new Client($account_sid, $auth_token);
$messages = $client->messages->create($number, array(
'From' => '+12533368077',
'Body' => Auth::user()->user_otp,
));
dd($messages);
//return $messages;
//throw new Exception();
} catch (Exception $e) {
return response()->json(['error' => true,'message'=>'Something went wrong'],200);
}
}
can you please help me with this

After setting env data did you clear cache?
php artisan config:cache
If you want to handle error - laravel has special logic for that. You need to just to catch that error and then make action, it is simple:
https://laravel.com/docs/5.6/errors
public function render($request, Exception $exception)
{
if ($exception instanceof CustomException) {
return response()->view('errors.custom', [], 500);
}
return parent::render($request, $exception);
}

Related

Using Symfony HTTP client with try and catch

I am using Symfony HTTP client in an event subscriber and I set timeout to 0.1. The problem is I want the code to skip the HTTP request if took more than 0.1 second and it timedout and meanwhile no error/exception needs to be thrown. I tried try and catch but it does not work.
public function checkToken()
{
try {
$response = $this->client->request('POST','url/of/api', [
'json' => ['token' => $_ENV['USER_TOKEN']],
'timeout' => 0.1,
]);
}catch (\Exception $e){
}
}
Why it can not be handled via try and catch?
Its because responses are lazy in Symfony.
As this document mentioned:
https://symfony.com/doc/current/http_client.html#handling-exceptions
A solution is to call getContent method in try section.
private $client;
private $user_data;
public function __construct(HttpClientInterface $client)
{
$this->client = $client;
}
public function checkToken(RequestEvent $event)
{
try {
$response = $this->client->request('POST', 'url/of/api', [
'json' => ['token' => $_ENV['USER_TOKEN']],
'timeout' => 0.1,
]);
$this->user_data = $response->getContent();
} catch (\Exception $e) {
echo $e->getMessage();
}
}

How to show exception in jwt laravel 5.4 api in postmen

In my laravel app i have installed jwt packages and set the middleware but the the token is invalid or expired or not sent it shows an error not in JSON format bellow are the details of my problems. Every things is working correctly but exception not throw in json format.Exception thrown as error like this (Could not decode token: Error while decoding to JSON: Malformed UTF-8 characters, possibly incorrectly encoded) that is the issue.
this is my jwtMiddleware
public function handle($request, Closure $next)
{
try
{
$user = JWTAuth::parseToken()->authenticate();
}
catch (\JWTException $e)
{
if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenInvalidException)
{
return response()->json(['status' => 'Token is Invalid']);
}
else if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException)
{
return response()->json(['status' => 'Token is Expired']);
}
else
{
return response()->json(['status' => 'Authorization Token not found']);
}
return response()->json(['status' => $e]);
}
return $next($request);
}
this is the error shows as shown in image
shown exception as error
and expected error like this
required exception
sending postman request
sending to postman
Check that the request that you're sending has this header
{ Authorization: 'Bearer TOKEN' }
How to add this header in Axios:
axios.interceptors.request.use(request => {
if (store.getters.authToken) {
request.headers.common['Authorization'] = `Bearer ${store.getters.authToken}`
}
return request
})
Check that your .htaccess has the rule
RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
I show my exception in json formate below way, you can try with this. to show exception in jwt you give this in catch JWTException
$credentials = $request->only('user_name', 'password');
try {
if (! $token = JWTAuth::attempt($credentials)) {
return response()->json([
'code' => 404,
'response' => 'error',
'errors' => ['massage' => 'invalid email/ or password.']
]);
}
} catch (JWTException $e) {
return response()->json([
'code' => 500,
'response' => 'error',
'errors' => ['massage' => 'failed to create token.']
]);
}

skip symfony2 kernel exception

I am using symfony2.8 and
We have a KernelExceptionService and I want to skip it if there is any Exception like 500,400 or any and get back to service and continue the work.
The reason
We are hitting multiple url to fetch the data and if there is any exception occurred whole processing get stopped.
public function onKernelException(GetResponseForExceptionEvent $event) {
$exception = $event->getException();
$response = new JsonResponse;
$request = $event->getRequest();
if ($exception instanceof InvalidConfigurationException) {
//500 case
$responseData = return [
'code' => Response::HTTP_NOT_FOUND,
'message' => $exception->getMessage()
];
} else {
// same as aobve if with difference code
}
//Prepare the response
$response->setData($responseData);
$response->setStatusCode($statusCode);
$event->setResponse($response);
}
Just wrap the particular code with a try catch block?
That way your exception listener will never trigger and you can handle the exception differently in that specific part of code.

Cakephp 3 get last query executed

I've been trying to handle exceptions on cakephp 3 when querying to database.
I would like to get the last query executed when and exception is fired to notify by email to an administrator, i'm using MySQL database so the error code would be nice to have it too if possible.
This is my code right now.
if($this->request->is('post')){
$opciones=$this->request->data;
$configsTable = TableRegistry::get('Configs');
try{
$configsTable->connection()->transactional(function() use($configsTable, $opciones){
foreach ($opciones as $llave => $opcion) {
$q = $configsTable->find('all', [
'conditions' => [
'Configs.nombre' => $llave
]
]);
$reg = $q->first();
if (empty($reg)) {
$data = array();
$data['nombre'] = $llave;
$data['valor'] = $opcion;
$entity = $configsTable->newEntity($data);
if (!$configsTable->save($entity, ['atomic' => false])) {
/********trying to catch database error here******/
throw new \Exception(__('Error message'));
}
}else{
$u = $configsTable->updateAll(['valor'=>$opcion], [
'id'=>$reg->id
]);
if(!$u){
/********trying to catch database error here******/
throw new \Exception(__('Error message'));
}
}
}
});
$this->Flash->success(__('Ajustes actualizados'),[
'params'=>['class'=>'alert-absolute timed', 'tiempo'=>5]
]);
} catch (\PDOException $ex) {
$this->Flash->error($ex->getCode().' - '.$ex->getMessage(),[
//'params'=>['class'=>'alert-absolute timed', 'tiempo'=>5]
]);
} catch (\Exception $ex){
$this->Flash->error($ex->getMessage(),[
//'params'=>['class'=>'alert-absolute timed', 'tiempo'=>5]
]);
}
}
I'm still searching on cookbook for some information. Thaks.
Let the PDOException be handled by the error handler (which is done by default). You can setup your own error handler which checks exception type and sends email in case of PDOException.
You can get the sql query using exception instance as $error->queryString.

Zend Framework 2 AbstractRestfulController - Exceptions as JSON

My goal is get a JSON like
{
"meta": {
"error_type": "error type",
"code": 400,
"error_message": "error msg"
}
}
In case something went wrong.
I tried to put the try catch block both in the rest controller's action and in the model but I get the whole exception stack (I mean with the layout + view)
What's the right way ?
Catch the exception in the controller action.
Return a JsonModel from the action containing exception information:
public function someAction()
{
try {
throw new Exception();
}
catch (Exception $e) {
return new JsonModel(array(
'meta' => array(
'code' => $e->getCode(),
'error_message' => $e->getMessage(),
//...
)
));
}
//...
}
Source: Returning JSON from a ZF2 controller action
[I tried to put the try catch block both in the action rest
controller]
I've just tried like
(I want my goal become true but
when only if something goes wrong :) )
public function create($data)
{
try{
$artist = $this->getRequest()->getPost('artist', null);
$title = $this->getRequest()->getPost('title', null);
$album = new Album();
$album->exchangeArray(array('artist'=>$artist,'title'=>$title));
$id = $this->getAlbumTable()->saveAlbum($album);
return $this->get($id);
}
catch (Exception $e) {
return new JsonModel(array(
'meta' =>array(
'code'=>500,
'error-num'=>$e->getCode(),
'error-msg'=>$e->getMessage(),
)
));
}
}
but as above it doesn't work
instead of json data i get the
whole default exception stack with layout.

Categories