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

An article explaining in detail how to handle exceptions in Laravel

青灯夜游
青灯夜游 forward
2022-10-02 06:00:27 2760browse

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 theconfig/app.phpfile 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 toTRUE, it will help us debug errors generated by the application. The default value is specified by theAPP_DEBUGparameter in the.envenvironment variable configuration file.

In the development environment, it is recommended that you set it toTRUE. 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 theconfig/app.phpfile 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 isstorage/logs/laravel.log. Normally, you do not need to change it. At the same time, you can passAPP_LOG_LEVELto 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 theapp/Exceptions/Handler.phpfile.

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 thereportmethod.

/** * 报告或记录一个异常。 * * 这是一个将异常发送给 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 importantdontReportattribute, which lists all exception categories that should not be logged.

Next, we introduce therendermethod.

/** * 将异常渲染至 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 thereportmethod is used to record or report errors, then therendermethod 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

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

Finally, theunauthenticatedmethod handles theAuthenticationExceptionexception, 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 theCustomExceptioncategory. The idea behind creating a custom exception class is to more easily manage custom exceptions while displaying custom responses.

Start creating a fileapp/Exceptions/CustomException.phpwith the following content.

view( 'errors.custom', array( 'exception' => $this ) ); } }

It is important to note that theCustomExceptionclass must inherit the coreExceptionclass. 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 theerrors.customerror page. This way you can implement custom error pages for specific types of exceptions.

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

Exception details: {{ $exception->getMessage() }}

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 theapp/Exceptions/Handler.phpfile to ensure that our custom exception class can be called. Let’s replace the render method in theapp/Exceptions/Handler.phpfile 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 controlapp/Http/Controllers/ExceptionController.phpto test the custom exception class.


      

当然,你需要先在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.com. If there is any infringement, please contact admin@php.cn delete