Home > PHP Framework > Laravel > An article explaining in detail how to handle exceptions in Laravel

An article explaining in detail how to handle exceptions in Laravel

青灯夜游
Release: 2022-10-02 06:00:27
forward
2941 people have browsed it

An article explaining in detail how to handle exceptions in Laravel

In this article, we will explore one of the most important and least discussed features of the Laravel web framework - Exception handling. Laravel comes with a built-in exception handler that allows you to easily report and present exceptions in a friendly way.

In the first half of the article, we will explore the default settings provided by exception handlers. In fact, we will first understand how Laravel handles exceptions through the default Handler class.

In the second half of the article, we will continue to introduce how to create a custom exception handler so that you can catch custom exceptions.

Basic configuration

Before starting to study the exception handling class, let us first take a look at several important parameter configurations related to exceptions.

Open the config/app.php file and look carefully at the following code snippet.

...
...
/*
|--------------------------------------------------------------------------
| 应用的调试模式
|--------------------------------------------------------------------------
|
| 当引用处于调试模式,将会显示错误产生式的详细堆栈信息
| 如果禁用,则只显示一个简单的错误页面
|
*/

'debug' => env('APP_DEBUG', false),
...
...
Copy after login

As you can guess from the name of the parameter, if set to TRUE, it will help us debug errors generated by the application. The default value is specified by the APP_DEBUG parameter in the .env environment variable configuration file.

In the development environment, it is recommended that you set it to TRUE. In this way, through clear error stack information, you can quickly locate the cause of the error and fix it. In addition, when in the formal environment, we need to turn it off through the configuration item of the environment variable. When an error occurs, only a general prompt page will be displayed.

In addition to displaying errors on the page, Laravel also allows you to log errors to a log file. Now, let's take a look at the logging related configuration. Open the config/app.php file and take a closer look at the following code snippet.

...
...
'log' => env('APP_LOG', 'single'),

'log_level' => env('APP_LOG_LEVEL', 'debug'),
...
...
Copy after login

In the Laravel framework, the Monolog library is used to record logs. You can configure the Monolog library through the above configuration items.

The default log file saving path is storage/logs/laravel.log. Normally, you do not need to change it. At the same time, you can pass APP_LOG_LEVEL to specify the error level that needs to be logged to the log file.

The basic configuration of exceptions and logs was introduced earlier.

Next, let’s take a look at the default exception handling class for Laravel applications. Open the app/Exceptions/Handler.php file.

<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    /**
     * 定义无需报告的异常类型
     *
     * @var array
     */
    protected $dontReport = [
        \Illuminate\Auth\AuthenticationException::class,
        \Illuminate\Auth\Access\AuthorizationException::class,
        \Symfony\Component\HttpKernel\Exception\HttpException::class,
        \Illuminate\Database\Eloquent\ModelNotFoundException::class,
        \Illuminate\Session\TokenMismatchException::class,
        \Illuminate\Validation\ValidationException::class,
    ];

    /**
     * 报告或者通过日志记录一个异常
     *
     * 可以在这个方法中将异常报告给 Sentry, Bugsnag 等平台
     *
     * @param  \Exception  $exception
     * @return void
     */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    /**
     * 将异常通过 Http 返回
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        return parent::render($request, $exception);
    }

    /**
     * 将认证相关的异常转换为未认证的响应(401)
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Auth\AuthenticationException  $exception
     * @return \Illuminate\Http\Response
     */
    protected function unauthenticated($request, AuthenticationException $exception)
    {
        if ($request->expectsJson()) {
            return response()->json(['error' => 'Unauthenticated.'], 401);
        }

        return redirect()->guest(route('login'));
    }
}
Copy after login

The above processing class mainly contains 2 functions: reporting and displaying all exception information.

Let's take a closer look at the report method.

/**
 * 报告或记录一个异常。
 *
 * 这是一个将异常发送给 Sentry 和 Bugsnag 等机构的好时机。
 *
 * @param  \Exception  $exception
 * @return void
 */
public function report(Exception $exception)
{
    parent::report($exception);
}
Copy after login

The report method is used to log errors to the log file. At the same time, pay attention to an important dontReport attribute, which lists all exception categories that should not be logged.

Next, we introduce the render method.

/**
 * 将异常渲染至 HTTP 响应值中。
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Exception  $exception
 * @return \Illuminate\Http\Response
 */
public function render($request, Exception $exception)
{
    return parent::render($request, $exception);
}
Copy after login

If the report method is used to record or report errors, then the render method is used to render and display errors on the screen. In fact, this method determines what content will be displayed to the user when an exception occurs. The

render method also allows you to customize response values ​​for different categories of errors, which we will learn in the next chapter.

Finally, the unauthenticated method handles the AuthenticationException exception, where you can determine what content is displayed when the user accesses an unauthorized page.

Custom exception class

In this section, we will create a custom exception class to handle exceptions of the CustomException category. The idea behind creating a custom exception class is to more easily manage custom exceptions while displaying custom responses.

Start creating a file app/Exceptions/CustomException.php with the following content.

<?php

namespace App\Exceptions;

use Exception;

class CustomException extends Exception
{
    /**
     * 报告这个异常。
     *
     * @return void
     */
    public function report()
    {
    }

    /**
     * 将异常渲染至 HTTP 响应值中。
     *
     * @param  \Illuminate\Http\Request
     * @return \Illuminate\Http\Response
     */
    public function render($request)
    {
        return response()->view(
                'errors.custom',
                array(
                    'exception' => $this
                )
        );
    }
}
Copy after login

It is important to note that the CustomException class must inherit the core Exception class. For demonstration purposes, we only discussed the render method, but obviously you can also customize the report method.

As you can see, in the example we redirect the user to the errors.custom error page. This way you can implement custom error pages for specific types of exceptions.

Of course, we need to create an associated view file resources/views/errors/custom.blade.php.

Exception details: <b>{{ $exception->getMessage() }}</b>
Copy after login

This is a fairly simple view file that only displays a one-line error message, but you can design the view any way you want.

We also need to make some modifications in the render method of the app/Exceptions/Handler.php file to ensure that our custom exception class can be called. Let’s replace the render method in the app/Exceptions/Handler.php file with the following.

...
...
/**
 * 将异常渲染至 HTTP 响应值中。
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Exception  $exception
 * @return \Illuminate\Http\Response
 */
public function render($request, Exception $exception)
{
    if ($exception instanceof \App\Exceptions\CustomException)  {
        return $exception->render($request);
    }

    return parent::render($request, $exception);
}
...
...
Copy after login

As you can see, we will first check the type of exception in the render method. If the exception's category is \App\Exceptions\CustomException, we will call the render method of this class.

everything's ready. Now we create a control app/Http/Controllers/ExceptionController.php to test the custom exception class.

<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;

class ExceptionController extends Controller
{
    public function index()
    {
        // 出错了,你可以抛出自定义的异常 CustomException
        throw new \App\Exceptions\CustomException('Something Went Wrong.');
    }
}
Copy after login

当然,你需要先在 routes/web.php 文件中添加相关的路由,就像下面一样。

// Exception routes
Route::get('exception/index', 'ExceptionController@index');
Copy after login

之后,你可以浏览 http://your-laravel-site.com/exception/ind... 地址来查看是否和预期的一样。一切正常的话,页面将显示我们前面配置 errors.custom 视图。

就这样,你就可以按自己方式来处理 Laravel 中的异常。
完!尽情享受 Laravel 带来的编码的乐趣吧!

总结

今天,我们认真学习了 Laravel 中的异常处理特性。在文章的开头,我们搜索了 Laravel 提供的一些基础配置,用于显示和报告异常。紧接着,我们简要介绍了默认的异常处理类。

在文章的后半部分,我们通过创建一个自定义异常处理类,演示如何在应用中处理自定义的异常。

对于那些刚刚起步学习 Laravel ,或者期待拓展阅读相关知识、网站、应用扩展的读者,这里有一系列您能够学习的内容,参见 Envato Market 。

期待听到任何形式的咨询或建议!

原文地址:https://code.tutsplus.com/tutorials/exception-handling-in-laravel--cms-30210

译文地址:https://learnku.com/laravel/t/8783/exception-handling-in-laravel

【相关推荐:laravel视频教程

The above is the detailed content of An article explaining in detail how to handle exceptions in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template