Laravel核心解读之异常处理的实践过程
前言
异常处理是编程中十分重要但也最容易被人忽视的语言特性,它为开发者提供了处理程序运行时错误的机制,对于程序设计来说正确的异常处理能够防止泄露程序自身细节给用户,给开发者提供完整的错误回溯堆栈,同时也能提高程序的健壮性。
这篇文章我们来简单梳理一下laravel中提供的异常处理能力,然后讲一些在开发中使用异常处理的实践,如何使用自定义异常、如何扩展laravel的异常处理能力。
下面话不多说了,来一起看看详细的介绍吧
注册异常handler
这里又要回到我们说过很多次的kernel处理请求前的bootstrap阶段,在bootstrap阶段的illuminate\foundation\bootstrap\handleexceptions 部分中laravel设置了系统异常处理行为并注册了全局的异常处理器:
class handleexceptions { public function bootstrap(application $app) { $this->app = $app; error_reporting(-1); set_error_handler([$this, 'handleerror']); set_exception_handler([$this, 'handleexception']); register_shutdown_function([$this, 'handleshutdown']); if (! $app->environment('testing')) { ini_set('display_errors', 'off'); } } public function handleerror($level, $message, $file = '', $line = 0, $context = []) { if (error_reporting() & $level) { throw new errorexception($message, 0, $level, $file, $line); } } }
set_exception_handler([$this, 'handleexception'])
将handleexceptions的handleexception方法注册为程序的全局处理器方法:
public function handleexception($e) { if (! $e instanceof exception) { $e = new fatalthrowableerror($e); } $this->getexceptionhandler()->report($e); if ($this->app->runninginconsole()) { $this->renderforconsole($e); } else { $this->renderhttpresponse($e); } } protected function getexceptionhandler() { return $this->app->make(exceptionhandler::class); } // 渲染cli请求的异常响应 protected function renderforconsole(exception $e) { $this->getexceptionhandler()->renderforconsole(new consoleoutput, $e); } // 渲染http请求的异常响应 protected function renderhttpresponse(exception $e) { $this->getexceptionhandler()->render($this->app['request'], $e)->send(); }
在处理器里主要通过exceptionhandler的report方法上报异常、这里是记录异常到storage/laravel.log文件中,然后根据请求类型渲染异常的响应生成输出给到客户端。这里的exceptionhandler就是\app\exceptions\handler类的实例,它是在项目最开始注册到服务容器中的:
// bootstrap/app.php /* |-------------------------------------------------------------------------- | create the application |-------------------------------------------------------------------------- */ $app = new illuminate\foundation\application( realpath(__dir__.'/../') ); /* |-------------------------------------------------------------------------- | bind important interfaces |-------------------------------------------------------------------------- */ ...... $app->singleton( illuminate\contracts\debug\exceptionhandler::class, app\exceptions\handler::class );
这里再顺便说一下set_error_handler函数,它的作用是注册错误处理器函数,因为在一些年代久远的代码或者类库中大多是采用php那件函数trigger_error函数来抛出错误的,异常处理器只能处理exception不能处理error,所以为了能够兼容老类库通常都会使用set_error_handler注册全局的错误处理器方法,在方法中捕获到错误后将错误转化成异常再重新抛出,这样项目中所有的代码没有被正确执行时都能抛出异常实例了。
/** * convert php errors to errorexception instances. * * @param int $level * @param string $message * @param string $file * @param int $line * @param array $context * @return void * * @throws \errorexception */ public function handleerror($level, $message, $file = '', $line = 0, $context = []) { if (error_reporting() & $level) { throw new errorexception($message, 0, $level, $file, $line); } }
常用的laravel异常实例
laravel中针对常见的程序异常情况抛出了相应的异常实例,这让开发者能够捕获这些运行时异常并根据自己的需要来做后续处理(比如:在catch中调用另外一个补救方法、记录异常到日志文件、发送报警邮件、短信)
在这里我列一些开发中常遇到异常,并说明他们是在什么情况下被抛出的,平时编码中一定要注意在程序里捕获这些异常做好异常处理才能让程序更健壮。
- illuminate\database\queryexception laravel中执行sql语句发生错误时会抛出此异常,它也是使用率最高的异常,用来捕获sql执行错误,比方执行update语句时很多人喜欢判断sql执行后判断被修改的行数来判断update是否成功,但有的情景里执行的update语句并没有修改记录值,这种情况就没法通过被修改函数来判断update是否成功了,另外在事务执行中如果捕获到queryexception 可以在catch代码块中回滚事务。
- illuminate\database\eloquent\modelnotfoundexception 通过模型的findorfail和firstorfail方法获取单条记录时如果没有找到会抛出这个异常(find和first找不到数据时会返回null)。
- illuminate\validation\validationexception 请求未通过laravel的formvalidator验证时会抛出此异常。
- illuminate\auth\access\authorizationexception 用户请求未通过laravel的策略(policy)验证时抛出此异常
- symfony\component\routing\exception\methodnotallowedexception 请求路由时http method不正确
- illuminate\http\exceptions\httpresponseexception laravel的处理http请求不成功时抛出此异常
扩展laravel的异常处理器
上面说了laravel把\app\exceptions\handler 注册成功了全局的异常处理器,代码中没有被catch到的异常,最后都会被\app\exceptions\handler捕获到,处理器先上报异常记录到日志文件里然后渲染异常响应再发送响应给客户端。但是自带的异常处理器的方法并不好用,很多时候我们想把异常上报到邮件或者是错误日志系统中,下面的例子是将异常上报到sentry系统中,sentry是一个错误收集服务非常好用:
public function report(exception $exception) { if (app()->bound('sentry') && $this->shouldreport($exception)) { app('sentry')->captureexception($exception); } parent::report($exception); }
还有默认的渲染方法在表单验证时生成响应的json格式往往跟我们项目里统一的josn格式不一样这就需要我们自定义渲染方法的行为。
public function render($request, exception $exception) { //如果客户端预期的是json响应, 在api请求未通过validator验证抛出validationexception后 //这里来定制返回给客户端的响应. if ($exception instanceof validationexception && $request->expectsjson()) { return $this->error(422, $exception->errors()); } if ($exception instanceof modelnotfoundexception && $request->expectsjson()) { //捕获路由模型绑定在数据库中找不到模型后抛出的notfoundhttpexception return $this->error(424, 'resource not found.'); } if ($exception instanceof authorizationexception) { //捕获不符合权限时抛出的 authorizationexception return $this->error(403, "permission does not exist."); } return parent::render($request, $exception); }
自定义后,在请求未通过formvalidator验证时会抛出validationexception, 之后异常处理器捕获到异常后会把错误提示格式化为项目统一的json响应格式并输出给客户端。这样在我们的控制器中就完全省略了判断表单验证是否通过如果不通过再输出错误响应给客户端的逻辑了,将这部分逻辑交给了统一的异常处理器来执行能让控制器方法瘦身不少。
使用自定义异常
这部分内容其实不是针对laravel框架自定义异常,在任何项目中都可以应用我这里说的自定义异常。
我见过很多人在repository或者service类的方法中会根据不同错误返回不同的数组,里面包含着响应的错误码和错误信息,这么做当然是可以满足开发需求的,但是并不能记录发生异常时的应用的运行时上下文,发生错误时没办法记录到上下文信息就非常不利于开发者进行问题定位。
下面的是一个自定义的异常类
namespace app\exceptions\; use runtimeexception; use throwable; class usermanageexception extends runtimeexception { /** * the primitive arguments that triggered this exception * * @var array */ public $primitives; /** * queuemanageexception constructor. * @param array $primitives * @param string $message * @param int $code * @param throwable|null $previous */ public function __construct(array $primitives, $message = "", $code = 0, throwable $previous = null) { parent::__construct($message, $code, $previous); $this->primitives = $primitives; } /** * get the primitive arguments that triggered this exception */ public function getprimitives() { return $this->primitives; } }
定义完异常类我们就能在代码逻辑中抛出异常实例了
class userrepository { public function updateuserfavorites(user $user, $favoritedata) { ...... if (!$executionone) { throw new usermanageexception(func_get_args(), 'update user favorites error', '501'); } ...... if (!$executiontwo) { throw new usermanageexception(func_get_args(), 'another error', '502'); } return true; } } class usercontroller extends ... { public function updatefavorites(user $user, request $request) { ....... $favoritedata = $request->input('favorites'); try { $this->userrepo->updateuserfavorites($user, $favoritesdata); } catch (usermanageexception $ex) { ....... } } }
除了上面repository列出的情况更多的时候我们是在捕获到上面列举的通用异常后在catch代码块中抛出与业务相关的更细化的异常实例方便开发者定位问题,我们将上面的updateuserfavorites 按照这种策略修改一下
public function updateuserfavorites(user $user, $favoritedata) { try { // database execution // database execution } catch (queryexception $queryexception) { throw new usermanageexception(func_get_args(), 'error message', '501' , $queryexception); } return true; }
在上面定义usermangeexception类的时候第四个参数$previous是一个实现了throwable接口类实例,在这种情景下我们因为捕获到了queryexception的异常实例而抛出了usermanagerexception的实例,然后通过这个参数将queryexception实例传递给php异常的堆栈,这提供给我们回溯整个异常的能力来获取更多上下文信息,而不是仅仅只是当前抛出的异常实例的上下文信息, 在错误收集系统可以使用类似下面的代码来获取所有异常的信息。
while($e instanceof \exception) { echo $e->getmessage(); $e = $e->getprevious(); }
异常处理是php非常重要但又容易让开发者忽略的功能,这篇文章简单解释了laravel内部异常处理的机制以及扩展laravel异常处理的方式方法。更多的篇幅着重分享了一些异常处理的编程实践,这些正是我希望每个读者都能看明白并实践下去的一些编程习惯,包括之前分享的interface的应用也是一样。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。
上一篇: 函数式编程入门实践(一)
下一篇: android使用mysql的方法总结