search
HomePHP FrameworkLaravelAn article explaining in detail how to handle exceptions in Laravel

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),
...
...

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'),
...
...

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

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

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

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

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>

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

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(&#39;Something Went Wrong.&#39;);
    }
}

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

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

之后,你可以浏览 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!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
Laravel's Impact: Simplifying Web DevelopmentLaravel's Impact: Simplifying Web DevelopmentApr 21, 2025 am 12:18 AM

Laravel stands out by simplifying the web development process and delivering powerful features. Its advantages include: 1) concise syntax and powerful ORM system, 2) efficient routing and authentication system, 3) rich third-party library support, allowing developers to focus on writing elegant code and improve development efficiency.

Laravel: Frontend or Backend? Clarifying the Framework's RoleLaravel: Frontend or Backend? Clarifying the Framework's RoleApr 21, 2025 am 12:17 AM

Laravelispredominantlyabackendframework,designedforserver-sidelogic,databasemanagement,andAPIdevelopment,thoughitalsosupportsfrontenddevelopmentwithBladetemplates.

Laravel vs. Python: Exploring Performance and ScalabilityLaravel vs. Python: Exploring Performance and ScalabilityApr 21, 2025 am 12:16 AM

Laravel and Python have their own advantages and disadvantages in terms of performance and scalability. Laravel improves performance through asynchronous processing and queueing systems, but due to PHP limitations, there may be bottlenecks when high concurrency is present; Python performs well with the asynchronous framework and a powerful library ecosystem, but is affected by GIL in a multi-threaded environment.

Laravel vs. Python (with Frameworks): A Comparative AnalysisLaravel vs. Python (with Frameworks): A Comparative AnalysisApr 21, 2025 am 12:15 AM

Laravel is suitable for projects that teams are familiar with PHP and require rich features, while Python frameworks depend on project requirements. 1.Laravel provides elegant syntax and rich features, suitable for projects that require rapid development and flexibility. 2. Django is suitable for complex applications because of its "battery inclusion" concept. 3.Flask is suitable for fast prototypes and small projects, providing great flexibility.

Frontend with Laravel: Exploring the PossibilitiesFrontend with Laravel: Exploring the PossibilitiesApr 20, 2025 am 12:19 AM

Laravel can be used for front-end development. 1) Use the Blade template engine to generate HTML. 2) Integrate Vite to manage front-end resources. 3) Build SPA, PWA or static website. 4) Combine routing, middleware and EloquentORM to create a complete web application.

PHP and Laravel: Building Server-Side ApplicationsPHP and Laravel: Building Server-Side ApplicationsApr 20, 2025 am 12:17 AM

PHP and Laravel can be used to build efficient server-side applications. 1.PHP is an open source scripting language suitable for web development. 2.Laravel provides routing, controller, EloquentORM, Blade template engine and other functions to simplify development. 3. Improve application performance and security through caching, code optimization and security measures. 4. Test and deployment strategies to ensure stable operation of applications.

Laravel vs. Python: The Learning Curves and Ease of UseLaravel vs. Python: The Learning Curves and Ease of UseApr 20, 2025 am 12:17 AM

Laravel and Python have their own advantages and disadvantages in terms of learning curve and ease of use. Laravel is suitable for rapid development of web applications. The learning curve is relatively flat, but it takes time to master advanced functions. Python's grammar is concise and the learning curve is flat, but dynamic type systems need to be cautious.

Laravel's Strengths: Backend DevelopmentLaravel's Strengths: Backend DevelopmentApr 20, 2025 am 12:16 AM

Laravel's advantages in back-end development include: 1) elegant syntax and EloquentORM simplify the development process; 2) rich ecosystem and active community support; 3) improved development efficiency and code quality. Laravel's design allows developers to develop more efficiently and improve code quality through its powerful features and tools.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor