Error Handling in Laravel

Mantan Programmer
Geek Culture
Published in
5 min readAug 9, 2022

--

Hello, how are you all friends, I hope you are all healthy and successful. This time we will discuss a tutorial on how to find errors that occur in Laravel.

Laravel gives you so much flexibility when it comes to error handling. I’m sure you’ll learn something new in this tutorial. You can override any of the laravel status code templates.

And you can study other tutorials:

Creating Ratings and Reviews With Laravel

Drag and Drop Image/File Upload Using Laravel

REST API Login & Register With Sanctum Laravel

One of the main features in Laravel for handling errors is exception handling. Laravel comes with a built-in exception handler that allows you to report and create exceptions in an easy and friendly way.

In the default settings provided by the exception handler is through the handler class to understand how laravel handles exceptions. and we’ll see how we can create an exception handler to be able to create custom exceptions.

HTTP Response Code and Status

CodeStatusDescription200OkThe request was successfully completed.201CreatedA new reesource was successfully created.400Bad RequestThe request was invalid.401UnauthorizedInvalid login credentials.403ForbiddenYou do not have enough permissions to perform this action.404Not FoundThe requested resource/page not found.405Method Not AllowedThis request is not supported by the resource.409ConflictThe request could not be completed due to a conflict.500Internal Server ErrorThe request was not completed due to an internal error on the server side.503Service UnavailableThe server was unavailable.

You must follow the file structure as mentioned above otherwise you will not be able to replace the above error page. To get the error message in the view file, you can use the following variables in your blade view:

404.blade.php

{{ $exception->getMessage() }}

Install Laravel

the first thing you have to start the application is, we have to install laravel first.

composer create-project laravel/laravel handling-laravel

Config Pengaturan Settings

After we install laravel, this time we can set our config file in config/app.php.

if it is set to TRUE it will help you to debug the error generated by the app. The default value of this variable is set to the value of the environment variable APP_DEBUGin the file .env

In the development environment, you should set it to TRUE so that you can easily track errors and fix them. On the other hand, you should turn it off in a production environment, and it will display a general error page in this case.

The standard log file is located at storage/logs/laravel.log, and is sufficient in most cases. On the other hand, APP_LOG_LEVEL is set to a value indicating the severity of the error to be logged.

Hendler Settings

Next, we’ll take a look at the default Handler class that comes with the default Laravel application. Go ahead and open the app/Exceptions/Handler.php file.

And you guys want to create custom response or view for your custom error you can do it in laravel. What you need to do is modify the App\Exceptions\Handler class.

<?phpnamespace App\Exceptions;use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;
use Illuminate\Http\Request;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that are not reported.
*
* @var array
*/
protected $dontReport = [
//
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* @var array
*/
protected $dontFlash = [
'current_password',
'password',
'password_confirmation',
];
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->reportable(function (Throwable $e) {
return false;
});
}
/**
* @param Request $request
* @param Throwable $e
* @return JsonResponse|Response|\Symfony\Component\HttpFoundation\Response
* @throws Throwable
*/
public function render($request, Throwable $e)
{
if ($request->is('api/*')) {
return response()->json([
'message' => 'Record not found.'
], 404);
}
return parent::render($request, $e);
}
}

You guys can add some other custom logic here to meet your exclusion requirements.

Error handling using register method

You can also render different error pages using laravel register method inside your App\Exceptions\Handler class. Let’s take an example let’s create a new exception class which will be called when the order fails in our application.

To generate a new exception class, follow the below command:

php artisan make:exception InvalidOrderException

The above command will create a file under the app/Exceptions folder with the name InvalidOrderException.php. Mari kita buka file baru ini dan modifikasi seperti yang ditunjukkan di bawah ini:

<?phpnamespace App\Exceptions;use Exception;class InvalidOrderException extends Exception
{
/**
* Get the exception's context information.
*
* @return array
*/
public function context(): array
{
return ['order_id' => 123];
}
}

Let’s modify our App\Exceptions\Handler class as shown below:

<?phpnamespace App\Exceptions;use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;
use Illuminate\Http\Request;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that are not reported.
*
* @var array
*/
protected $dontReport = [
//
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* @var array
*/
protected $dontFlash = [
'current_password',
'password',
'password_confirmation',
];
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->renderable(function (InvalidOrderException $e, $request) {
return response()->view('errors.invalid-order', [], 500);
});
}
}

Now, create a file named invalid-order.php under the app/resources/views/errors folder and modify the file contents as needed.

Thus the tutorial this time I bolt. May be useful.

Thanks.

--

--