How to catch all exceptions in Laravel - laravel

I was wondering if there is a way to catch all the exceptions that are thrown in a laravel app and store them in database ?
I have been looking at some packages but coudn't find anything that tells where and how to catch the exceptions.

for catch all errors and log them you need to edit App\Exceptions\Handler file like this
public function render($request, Exception $exception)
{
if ($exception){
// log the error
return response()->json([
'status' => $exception->getStatusCode(),
'error' => $exception->getMessage()
]);
}
return parent::render($request, $exception);
}

As stated in the Docs,
You need to have to customize the render() method of App\Exceptions\Handler.
Edit the app/Exceptions/Handler.php:
public function render($request, Exception $e)
{
$error =$e->getMessage();
//do your stuff with the error message
return parent::render($request, $exception);
}

Related

customize ExceptionHandler in findOrFail error message

Good morning all,
Laravel v7.+
I made a
$user = User::findOrFail($id);
on my controller, it works well but when I have no result it sends me to a 404 page.
I would like to be able to do a return back with error message.
Some are talking about try catch.
Do you have any other solution to optimize?
Thank you, good day, stay home!
If you are having this issue in a single Controller only, you can use try catch
If you need a more general solution, you can work with the exception render method (https://laravel.com/docs/master/errors#render-method) on the ModelNotFoundException
public function render($request, Throwable $exception)
{
if ($exception instanceof ModelNotFoundException) {
return response()->view('errors.custom', [], 404);
}
return parent::render($request, $exception);
}
Alternative to try/catch
$user = User::find($id);
if(!$user){
return redirect()->back()->with(['error' => 'Error message']);
}
... your other logic here

Exception Handling when using both web and token api gaurd

Using laravel5.8. Using both web and API(Token Gaurd).
when using api call with invalid api_token parameter receiving an error Route:Login not defined. I want the response in JSON. Read in Forum I need to use the below way in app\Exceptions\Handler.php and it works. I have web gaurd for some of the paths. I want the route:login to work when its a web gaurd and return json response when using api gaurd. How can I do it in Laravel 5.8?
public function render($request, Exception $exception)
{
// dd(get_class($exception));
// return parent::render($request, $exception);
return response()->json(
[
'errors' => [
'status' => 401,
'message' => 'Unauthenticated',
]
], 401
);
}
I put the logic in unauthenticated function, combines with expectsJson() should solve your problem
// in app\Exceptions\Handler.php
public function render($request, Exception $exception)
{
return parent::render($request, $exception);
}
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['status' => 401,'message' => 'Unauthenticated.'], 401);
}
return redirect()->guest('/');
}

Handle jwt auth errors in laravel

I'm working on a rest api project.
I was struggling with an issue. As I get the token expiration error, the generated code will be something like this :
public function authenticate(Request $request){
$this->checkForToken($request);
try {
if (! $this->auth->parseToken()->authenticate()) {
throw new UnauthorizedHttpException('jwt-auth', 'User not found');
}
} catch (JWTException $e) {
throw new UnauthorizedHttpException('jwt-auth', $e->getMessage(), $e, $e->getCode());
}
}
This code is written in this file :
vendor/tymon/jwt-auth/src/Http/Middleware/BaseMiddleware.php
How can I return this as a JSON type?
Catch that exception in your App\Exceptions\Handler class' render method and return a response formatted as json:
// Handler.php
// import the class of the exception you want to render a json response for at the top
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
...
public function render($request, Exception $exception)
{
// if your api client has the correct content-type this expectsJson()
// should work. if not you may use $request->is('/api/*') to match the url.
if($request->expectsJson())
{
if($exception instanceof UnauthorizedHttpException) {
return response()->json('Unauthorized', 403);
}
}
return parent::render($request, $e);
}

How to catch exception when Laravel cannot connect to Redis?

Iam using Redis as cache in Laravel.
But I cannot catch Exception when laravel cannot connect to Redis (redis stopped, ...). I want catch this exception to reponse to client by JSON.
How can I do it ?
You can use render() function of App\Exceptions\Handler class as:
public function render($request, Exception $exception)
{
if ($exception instanceof SomeRedisException) {
return response()->json('Redis Error',500);
}
return parent::render($request, $exception);
}
Docs
In case of Redis connection error - the RedisException will be thrown by phpredis extension.
Somewhere in your Controller or Middleware:
try {
// Call Laravel Cache facade when Redis connection is failing
// This will throw exception
Cache::get('cache_key');
} catch (RedisException $exception) {
// In case Redis error - do custom response
Log::error('Redis error', [
'message' => $exception->getMessage(),
'trace' => $exception->getTrace()
]);
return response()->json([
'error' => 'your error message to client'
]);
}

Laravel 5 Error Handling

I am using Laravel 5 and I am trying to make custom 404 page and custom Exception handling, but I can't figure out where to put my code. Some time ago there was an ErrorServiceProvider that no longer exists. Can anyone give me some pointers?
EDIT: I saw they have added a Handler class in the App/Exception folder but that still seems not the right place to put it because it does not follow at all the laravel 4.2 App::error, App::missing and App::fatal methods. Anyone has any ideas?
Use app/Exceptions/Handler.php render method to achieve that. L5 documentation http://laravel.com/docs/5.0/errors#handling-errors
public function render($request, Exception $e)
{
if ($e instanceof Error) {
if ($request->ajax()) {
return response(['error' => $e->getMessage()], 400);
} else {
return $e->getMessage();
}
}
if ($this->isHttpException($e)) {
return $this->renderHttpException($e);
} else {
return parent::render($request, $e);
}
}
Here is how to customize your error page while complying with the APP_DEBUG setting in .env.
app/Exceptions/Handler.php
public function render($request, Exception $e)
{
if ($this->isHttpException($e))
{
return $this->renderHttpException($e);
}
else
{
if (env('APP_DEBUG'))
{
return parent::render($request, $e);
}
return response()->view('errors.500', [], 500);
}
}

Resources