在本文中,我们将探讨Laravel Web框架最重要和讨论最少的功能之一-异常处理。 Laravel带有内置的异常处理程序,使您可以轻松友好地报告和呈现异常。
在本文的前半部分,我们将探讨异常处理程序提供的默认设置。 实际上,我们首先将遍历默认的Handler类,以了解Laravel如何处理异常。
在本文的后半部分,我们将继续学习如何创建一个自定义异常处理程序,以允许您捕获自定义异常。
设置先决条件
在我们继续直接进入Handler类之前,让我们看一下与异常相关的几个重要配置参数。
继续并打开config/app.php
文件。 让我们仔细看看以下代码片段。
...
...
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => env('APP_DEBUG', false),
...
...
顾名思义,如果将其设置为TRUE
,它将帮助您调试由应用程序生成的错误。 此变量的默认值设置为.env
文件中APP_DEBUG
环境变量的值。
在开发环境中,应将其设置为TRUE
以便可以轻松跟踪错误并进行修复。 另一方面,您想在生产环境中将其关闭,在这种情况下,它将显示一个通用错误页面。
除了显示错误之外,Laravel还允许您在日志文件中记录错误。 让我们快速查看可用于记录的选项。 再次,让我们切换到config/app.php
文件,并仔细查看以下代码段。
...
...
'log' => env('APP_LOG', 'single'),
'log_level' => env('APP_LOG_LEVEL', 'debug'),
...
...
由于Laravel使用Monolog PHP库进行日志记录,因此您应该在该库的上下文中设置以上选项。
默认日志文件位于storage/logs/laravel.log
,在大多数情况下足够了。 另一方面, APP_LOG_LEVEL
设置为一个值,该值指示将要记录的错误的严重性。
因此,这是对可用于异常和日志记录的配置选项的基本介绍。
接下来,让我们看一下默认Laravel应用程序附带的默认Handler类。 继续并打开app/Exceptions/Handler.php
文件。
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @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,
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $exception
* @return void
*/
public function report(Exception $exception)
{
parent::report($exception);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $exception
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $exception)
{
return parent::render($request, $exception);
}
/**
* Convert an authentication exception into an unauthenticated response.
*
* @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'));
}
}
处理程序类负责两个重要的功能-报告和呈现所有错误。
让我们仔细看一下report
方法。
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $exception
* @return void
*/
public function report(Exception $exception)
{
parent::report($exception);
}
报告方法用于将错误记录到日志文件中。 同时,注意dontReport
属性也很重要,该属性列出了所有不应记录的异常类型。
接下来,让我们引入render
方法。
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $exception
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $exception)
{
return parent::render($request, $exception);
}
如果report
方法用于记录或报告错误,则render
方法用于在屏幕上呈现错误。 实际上,此方法处理发生异常时将显示给用户的内容。
render
方法还允许您针对不同类型的异常来自定义响应,这将在下一节中介绍。
最后, unauthenticated
AuthenticationException
unauthenticated
方法将处理AuthenticationException
异常,该异常使您可以决定在unauthenticated
AuthenticationException
用户访问他们正在寻找的页面的情况下向用户显示的内容。
自定义异常类
在本节中,我们将创建一个处理CustomException
类型的异常的自定义异常类。 创建自定义异常类的想法是轻松管理自定义异常并同时呈现自定义响应。
继续创建具有以下内容的文件app/Exceptions/CustomException.php
。
<?php
namespace App\Exceptions;
use Exception;
class CustomException extends Exception
{
/**
* Report the exception.
*
* @return void
*/
public function report()
{
}
/**
* Render the exception into an HTTP response.
*
* @param \Illuminate\Http\Request
* @return \Illuminate\Http\Response
*/
public function render($request)
{
return response()->view(
'errors.custom',
array(
'exception' => $this
)
);
}
}
这里要注意的重要事情是CustomException
类必须扩展核心Exception
类。 出于演示目的,我们将仅讨论render方法,但是您当然也可以自定义报告方法。
如您所见,在这种情况下,我们会将用户重定向到errors.custom
错误页面。 这样,您可以为特定类型的异常实现自定义错误页面。
当然,我们需要在resources/views/errors/custom.blade.php
创建一个关联的视图文件。
Exception details: <b>{{ $exception->getMessage() }}</b>
那是一个显示错误消息的非常简单的视图文件,但是您当然可以按照自己的方式设计它。
我们还需要在app/Exceptions/Handler.php
文件的render方法中进行更改,以便可以调用我们的自定义异常类。 让我们用app/Exceptions/Handler.php
文件中的以下内容替换render方法。
...
...
/**
* Render an exception into an HTTP response.
*
* @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);
}
...
...
如您所见,我们首先在render方法中检查异常的类型。 如果异常的类型为\App\Exceptions\CustomException
,我们将调用该类的render方法。
因此,现在一切就绪。 接下来,让我们继续在app/Http/Controllers/ExceptionController.php
创建一个控制器文件,以便我们可以测试自定义异常类。
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
class ExceptionController extends Controller
{
public function index()
{
// something went wrong and you want to throw CustomException
throw new \App\Exceptions\CustomException('Something Went Wrong.');
}
}
当然,您需要在以下routes/web.php
中显示的routes/web.php
添加关联的路由。
// Exception routes
Route::get('exception/index', 'ExceptionController@index');
有了这个,您可以运行http://your-laravel-site.com/exception/index URL来查看它是否按预期工作。 它应该按照我们的配置显示errors.custom
视图。
这就是您应该在Laravel中处理自定义异常的方式。 这使我们到了本文的结尾-我希望您喜欢它!
结论
今天,我们经历了Laravel中的异常处理功能。 在本文的开头,我们探索了Laravel提供的基本配置,以呈现和报告异常。 此外,我们简要介绍了默认的异常处理程序类。
在本文的后半部分,我们准备了一个自定义异常处理程序类,该类演示了如何在应用程序中处理自定义异常。
对于那些刚刚开始使用Laravel或希望通过扩展来扩展您的知识,网站或应用程序的人,我们可以在Envato Market中进行很多研究。
我很乐意以询问和建议的形式收到您的来信!
翻译自: https://code.tutsplus.com/tutorials/exception-handling-in-laravel--cms-30210