Error logging is truncated in Laravel of Guzzle http - laravel

Guzzle http is truncating exceptions with more than 120 characters, but I need to log the full exception message. How can I do this?
I am using laravel 4.2.22.

try {
// whatever
} catch (\GuzzleHttp\Exception\RequestException $ex) {
return $ex->getResponse()->getBody()->getContents();
// you can even json_decode the response like json_decode($ex->getResponse()->getBody()->getContents(), true)
}

It is the same for Laravel 5 and 4
try {
$response = $client->post($path, $params);
} catch (\GuzzleHttp\Exception\RequestException $ex) {
\Log::debug('error');
\Log::debug((string) $ex->getResponse()->getBody());
throw $ex;
}
if you just go to $ex->getMessage(), you will get
(truncated...)
at the end.

Might be better solution:
try {
// do request here like:
// return $client->post($path, $params);
} catch (\GuzzleHttp\Exception\ServerException $ex) {
$exFactoryWithFullBody = new class('', $ex->getRequest()) extends \GuzzleHttp\Exception\RequestException {
public static function getResponseBodySummary(ResponseInterface $response)
{
return $response->getBody()->getContents();
}
};
throw $exFactoryWithFullBody->create($ex->getRequest(), $ex->getResponse());
}

Related

How can I handle a custom HTTP exception?

I created an exception called invalid balance, and I'm using like the following. My output result status is 500. How can I change this status to 400?
try {
$balance = Wallet::findOrFail()->docs()
->sum('amount');
if ($balance == 0) {
throw new InvalidBalance();
}
} catch (QueryException $e) {
$message = Str::contains($e->getMessage(), 'Deadlock') ?
'Server is busy' : $e->getMessage();
throw new HttpException(400, $message);
} catch (\Exception $e) {
throw $e;
}
You can use the abort helper.
if ($balance === 0)
{
abort(400, 'Bad Request.');
}
Or within the InvalidBalance class do the abort there.
You can use response() method and pass the http status code as the second parameter as in laravel helpers functions
return response()->json(['message'=>'your message'], 400);

Laravel return redirect in catch

I'm trying to learn laravel and I have redirect problems in catch clause.
The following code catches the exception but not redirects me to / path
even when I comment dd($e).
try {
DB::transaction(function() {
model1->save();
model2->save();
....
});
return redirect('/');
} catch (\Illuminate\Database\QueryException $e) {
dd($e);
return redirect('/');
}
Any idea?
#lagbox thx for help I got it... I just connected your stuff with my useless coding skills and I found out how dumb I am :/ . Actualy it s too late for coding but nvm :). So the solution is: In Model:
try{
DB::transaction(function(){
model1->save();
model2->save();
...
});
return true;
}catch (\Illuminate\Database\QueryException $e){
//dd($e);
return false;
}
Then in controller
`
if(!methodInModel){
return 123;
}
`

Laravel-Vue: How can I use try-catch block to catch validation exception in Validation Requests?

I'm using vue.js. I'm hitting my server with axios like:
try{
const resp = await axios.post('storeProduct', data,
{
headers : header(state)
});
console.log(resp);
}catch(error){
console.log("you are at error");
console.log(error);
}
Here, I'm console logging the error where I get error 422 but I want to get the message as well. If I use try catch in a simple validation it works. But cant make it working with the Validation Request object.
In my Controller: 'ProductRequest' is the validation object which has validation rules. It gives me the errors but can't catch in the try-block of axios in vue.
public function storeProduct(ProductRequest $request){
try{
return $controller->saveProducts($request);
}catch(\Exception $e){
return $e;
}
}
ProductRequest.php
public function rules()
{
try{
return validation_value('add_products');
}catch(\Exception $e){
return $e;
}
}
Is there anyway that I could return the error message from here and catch it in my 'vue axios try/catch block'
Try it like this :
axios.post('storeProduct', data,
{
headers : header(state)
})
.then(response => console.log(response.data))
.catch(error => {
if (error.response) {
console.log("you are at error");
console.log(error.response);
}
});

Undefined property: GuzzleHttp\Exception\ConnectException::$status

I keep getting this error when trying to get the status of the request.
This is my code
ExpenseRepository.php
<?php
namespace Expensetrim\Api\v1\Repositories;
use Auth;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Expensetrim\Models\Company;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class ExpenseRepository
{
private $api_url;
const API_GET = 'GET';
const API_POST = 'POST';
const API_PUT = 'PUT';
function __construct()
{
$this->api_url = "http://xxx-xxx-xxx/api/v1/";
}
public function api_call($method, $uri, $request = NULL)
{
try {
$url=$this->api_url.$uri;
$client = new Client(['base_uri' => $this->api_url]);
$response = ($request) ? $client->request($method, $uri, $request) : $client->request($method, $uri);
}
catch (RequestException $e) {
return $e;
}
return $this->formatResponseBody($response);
}
public static function formatResponseBody($response)
{
$body = $response->getBody(true)->getContents();
return json_decode($body);
}
public function addExpenseType($data)
{
$uri = 'expense/types/add';
$response = $this->api_call(self::API_POST, $uri, ['form_params' => $data]);
return $response;
}
Also CompanyRepository.php
public function addExpenseType($company_id, $data)
{
$data['company_id'] = $company_id;
$expense = new ExpenseRepository;
$done = $expense->addExpenseType($data);
if($done->status == 'success') {
return true;
}
return true;
}
I need to check if the status is a success or not but keep getting this error: Undefined property: GuzzleHttp\Exception\ConnectException::$status.
Please what am i doing wrong?
There is an exception thrown at this line:
catch (RequestException $e) {
return $e;
}
and you are returning the exception. The return value of the method addExpenseType is actually an exception thrown by Guzzle.
throw the exception to see the error.
change your code to
catch (RequestException $e) {
throw $e;
}
Change your formatResponseBody function to add $response->getBody()->rewind();
public static function formatResponseBody($response)
{
$response->getBody()->rewind();
$body = $response->getBody(true)->getContents();
return json_decode($body);
}
In the old version of guzzle, it read the full body without resetting the pointer after. Using rewind() will reset the pointer. If this is the source of your issue rewind() will resolve this. It has aleady been resolved in newer versions.

Throw an error in Laravel (not eloquent)

In my package I perform a check on a user id:
//check
if(!$this->checkId($id)) //error
If this fails I need to throw an error as the method in my package will fail to work and I need to inform the user.
Please note, this is not a eloquent query so I do not need any find or fail methods.
How can I do this in laravel?
I agree with the previous answer, but I would throw an exception from checkId() method - since either check passes or fails (and throws exception).
class CheckIdException extends Exception
{
}
class WhateverClass
{
public function checkId($id)
{
// do the check
$passes = ....
if (! $passes) {
throw new CheckIdException('CheckId() failed');
}
return true;
}
}
// somewhere in the app code
try {
$this->checkId($id);
} catch (CheckIdException $e) {
return Response::json(['error' => 'checkId', 'message' => 'meaningul error description']);
} catch (Exception $e) {
return Response::json(['error' => 'UnknownError', 'message' => $e->getMessage()]);
}
// yay, ID check passes! Continue!
...so just throw an error?
if(!$this->checkId($id)) //error
{
App::abort(500, 'CheckId() failed');
}
or
if(!$this->checkId($id)) //error
{
throw new Exception("CheckId() failed");
}

Resources