How can I handle a custom HTTP exception? - laravel

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);

Related

How to change the response messages in Tymon JWT package laravel

I want to change response messages in the Tymon JWT package. For example, while fetching the data with Invalid token I am getting this response
"message": "Invalid token.",
"exception": "Tymon\\JWTAuth\\Exceptions\\TokenInvalidException",
I need o change this from above response to below response
"errors": "Invalid token.",
"exception": "Tymon\\JWTAuth\\Exceptions\\TokenInvalidException",
controller code
try {
$assign = AssignmentResource::collection(DB::table('assignments')->whereIn('assignments.academic_id',$ids)
->whereIn('assignments.batch',$batch)
->whereIn('assignments.course',$classid)->get());
} catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
return response()->json(['success' => false,'errors' => $e,'status' => 404] );
} catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
return response()->json(['success' => false,'errors' =>$e,'status' => 404] );
} catch (Tymon\JWTAuth\Exceptions\JWTException $e) {
return response()->json(['success' => false,'errors' =>$e,'status' => 404] );
}
thank you in advance
You can customize the laravel Exceptions.
inside app/Exceptions/Handler.php you can customize your message.
public function render($request, Exception $exception)
{
if ($request->is('api/*') || $request->expectsJson() || $request->is('webhook/*')) {
if ($exception instanceof Tymon\JWTAuth\Exceptions\TokenInvalidExceptio) {
return [
'errors' => $exception->getMessage(),
'exception' => 'your message'
];
}
}
}
If you see Exception Handling page of Tymon JWT Auth, then it is coming soon:
One way you can achieve this is like using try..catch:
try {
// Your code here.
} catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
// return your response.
} catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
// return your response.
} catch (Tymon\JWTAuth\Exceptions\JWTException $e) {
// return your response.
}

Error logging is truncated in Laravel of Guzzle http

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());
}

Handling Client Errors exceptions on GuzzleHttp

im trying to handdle request status code, basically checking if the status is 200, in case that it isnt handle it. Im using a package called "GuzzleHttp\Client", when there is a 404 it gives me a error:
Client error: `GET https://api.someurl---` resulted in a `404 Not Found` response:
{"generated_at":"2017-09-01T16:59:25+00:00","schema":"","message":"No events scheduled for this date."}
But than in the screen is displayed in a format that i want to change, so im trying to catch and give a different output on the view. But is not working, it stills gives me the red screen error.
try {
$client = new \GuzzleHttp\Client();
$request = $client->request('GET', $url);
$status = $request->getStatusCode();
if($status == 200){
return $status;
}else{
throw new \Exception('Failed');
}
} catch (\GuzzleHttp\Exception\ConnectException $e) {
//Catch errors
return $e->getStatusCode();
}
Okay so if you want to stick with a try-catch you want to do something like this:
$client = new \GuzzleHttp\Client();
try {
$request = $client->request('GET', $url);
} catch (\GuzzleHttp\Exception\ConnectException $e) {
// This is will catch all connection timeouts
// Handle accordinly
} catch (\GuzzleHttp\Exception\ClientException $e) {
// This will catch all 400 level errors.
return $e->getResponse()->getStatusCode();
}
$status = $request->getStatusCode();
If the catch doesn't get triggered the $request would be successful meaning it'll have a status code of 200.
However to to catch the 400 error, ensure you've got http_errors request option is set to true when setting up the $client.

How to add custom error in Laravel?

How to call custmo error in controller, that after to show in template?
For example, I have condition:
if($id == 500){
// call error
}
If you want to call just the error in the controller and abort, you do
abort(500, 'Internal error');
If you want to return an error
return redirect()->back()->withErrors(['error' => 'was 500']);
You can do this by catching the error in the Handler (app/Exceptions/Handler.php), something like this:
public function render($request, Exception $e){
// other errors here by your wish
// custom error message
if ($e instanceof \ErrorException) {
return response()->view('errors.500', [], 500);
}else{
return parent::render($request, $e);
}
return parent::render($request, $e);
}
Note that you need 500 template in resources/views/errors/500.blade.php (create if it doesnt exist, and fill if with your data or iformation about the exception)

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