版权声明:本文为博主原创文章,未经博主允许不得转载。

Lumen的核心类Application引用了专门用于异常处理的RegistersExceptionHandlers,

class Application extends Container
{use Concerns\RoutesRequests,Concerns\RegistersExceptionHandlers;

直接来看一下这个引用里的方法RegistersExceptionHandlers.php

<?phpnamespace Laravel\Lumen\Concerns;use Error;
use ErrorException;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Debug\Exception\FatalErrorException;
use Symfony\Component\Debug\Exception\FatalThrowableError;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;trait RegistersExceptionHandlers
{/*** Throw an HttpException with the given data.(通过给定的数据HttpException。)** @param  int     $code* @param  string  $message* @param  array   $headers* @return void** @throws \Symfony\Component\HttpKernel\Exception\HttpException*/public function abort($code, $message = '', array $headers = []){if ($code == 404) {throw new NotFoundHttpException($message);}throw new HttpException($code, $message, null, $headers);}/*** Set the error handling for the application.(设置应用程序的错误处理。)** @return void*/protected function registerErrorHandling(){error_reporting(-1);set_error_handler(function ($level, $message, $file = '', $line = 0) {if (error_reporting() & $level) {throw new ErrorException($message, 0, $level, $file, $line);}});set_exception_handler(function ($e) {$this->handleUncaughtException($e);});register_shutdown_function(function () {$this->handleShutdown();});}/*** Handle the application shutdown routine.(处理关闭应用程序。)** @return void*/protected function handleShutdown(){if (! is_null($error = error_get_last()) && $this->isFatalError($error['type'])) {$this->handleUncaughtException(new FatalErrorException($error['message'], $error['type'], 0, $error['file'], $error['line']));}}/*** Determine if the error type is fatal.(如果确定的错误类型是致命的。)** @param  int  $type* @return bool*/protected function isFatalError($type){$errorCodes = [E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE];if (defined('FATAL_ERROR')) {$errorCodes[] = FATAL_ERROR;}return in_array($type, $errorCodes);}/*** Send the exception to the handler and return the response.(将异常发送给处理程序并返回响应。)** @param  \Throwable  $e* @return Response*/protected function sendExceptionToHandler($e){$handler = $this->resolveExceptionHandler();if ($e instanceof Error) {$e = new FatalThrowableError($e);}$handler->report($e);return $handler->render($this->make('request'), $e);}/*** Handle an uncaught exception instance.(处理未捕获的异常情况。)** @param  \Throwable  $e* @return void*/protected function handleUncaughtException($e){$handler = $this->resolveExceptionHandler();if ($e instanceof Error) {$e = new FatalThrowableError($e);}$handler->report($e);if ($this->runningInConsole()) {$handler->renderForConsole(new ConsoleOutput, $e);} else {$handler->render($this->make('request'), $e)->send();}}/*** Get the exception handler from the container.(从容器中获取异常处理程序。)** @return mixed*/protected function resolveExceptionHandler(){if ($this->bound('Illuminate\Contracts\Debug\ExceptionHandler')) {return $this->make('Illuminate\Contracts\Debug\ExceptionHandler');} else {return $this->make('Laravel\Lumen\Exceptions\Handler');}}
}

以上就是封装用于$app的几个异常处理方法了,接下来看一下Lumen对异常处理做的默认绑定,这里的单例绑定是接口绑定类的类型

$app->singleton(Illuminate\Contracts\Debug\ExceptionHandler::class,App\Exceptions\Handler::class
);

app/Exceptions/Handler.php

<?phpnamespace App\Exceptions;use Exception;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\HttpException;class Handler extends ExceptionHandler
{/*** A list of the exception types that should not be reported.(不应该报告的异常类型的列表。)** @var array*/protected $dontReport = [AuthorizationException::class,HttpException::class,ModelNotFoundException::class,ValidationException::class,];/*** Report or log an exception.(报告或记录异常。)** This is a great spot to send exceptions to Sentry, Bugsnag, etc.** @param  \Exception  $e* @return void*/public function report(Exception $e){parent::report($e);}/*** Render an exception into an HTTP response.(在HTTP响应中呈现异常。)** @param  \Illuminate\Http\Request  $request* @param  \Exception  $e* @return \Illuminate\Http\Response*/public function render($request, Exception $e){return parent::render($request, $e);}
}

这个类继承了一个实现Illuminate\Contracts\Debug\ExceptionHandler::class接口的异常处理基类Laravel\Lumen\Exceptions\Handler,这样,我们就可以很方便的做异常拦截和处理了!比如,

public function render($request, Exception $e){//数据验证异常拦截if ($e instanceof \Illuminate\Validation\ValidationException) {var_dump($e->validator->errors()->toArray());}return parent::render($request, $e);}

这样我们就监听拦截到了Validation的ValidationException的异常,其实这部分往深扒的话,还有很多东西,如symfony下的debug和http-kernel两个模块的包,可以研究下

Lumen技术交流群:310493206

版权声明:本文为博主原创文章,未经博主允许不得转载。

转载于:https://www.cnblogs.com/cxscode/p/7573381.html

Lumen开发:Lumen的异常处理机制相关推荐

  1. Go语言的错误异常处理机制及其应用

    一.背景 在日常编写golang程序或阅读别人的golang代码时,我们总会看到如下的一堆代码块: xx, err = func(xx) if err != nil {//do sth. to tac ...

  2. c语言c2182是什么错误,C语言中一种更优雅的异常处理机制

    上一篇文章对C语言中的goto语句进行了较深入的阐述,实际上goto语句是面向过程与面向结构化程序语言中,进行异常处理编程的最原始的支持形式.后来为了更好地.更方便地支持异常处理编程机制,使得程序员在 ...

  3. Laravel 5.5 的错误异常处理机制以及应用实例

    一.前言 我们在开发项目中,难免会因为逻辑上的失误而报错,这些报错的展现形式也就是框架封装好的异常处理机制.在项目上线之前,我们还可以根据框架提供的报错信息来锁定错误代码的位置.但是项目上线之后我们是 ...

  4. Java程序员从笨鸟到菜鸟之(十二)java异常处理机制

    异常处理是程序设计中一个非常重要的方面,也是程序设计的一大难点,从C开始,你也许已经知道如何用if...else...来控制异常了,也许是自发的,然而这种控制异常痛苦,同一个异常或者错误如果多个地方出 ...

  5. 深入理解java异常处理机制

    1. 引子 try-catch-finally恐怕是大家再熟悉不过的语句了,而且感觉用起来也是很简单,逻辑上似乎也是很容易理解.不过,我亲自体验的"教训"告诉我,这个东西可不是想象 ...

  6. python异常处理机制的好处_浅谈Python异常处理机制

    异常机制己经成为衡量一门编程语言是否成熟的标准之一,使用异常处理机制的 Python 程序有更好的容错性,更加健壮. 对于计算机程序而言,情况就更复杂了一一没有人能保证自己写的程序永远不会出辛苦!就算 ...

  7. Struts2异常处理机制

    任何成熟的MVC框架都应该提供成就的异常处理机制,Strut2也不例外.Struts2提供了一种声明式的异常处理方式,Struts2也是通过配置的拦截器来实现异常处理机制的. 一.  异常处理机制 1 ...

  8. Struts2学习笔记(五)之异常处理机制

    我们在知道在软件开发中的异常处理是很重要的,作为成熟的MVC框架的Struts2也提供了异常处理处理机制,对于一场处理:用户发送请求-->Action控制器-->发现相应的异常--> ...

  9. java 异常机制_深入理解Java异常处理机制

    一.引子 try-catch-finally恐怕是大家再熟悉不过的语句了,而且感觉用起来也是很简单,逻辑上似乎也是很容易理解.不过,我亲自体验的"教训"告诉我,这个东西可不是想象中 ...

  10. python提供什么机制处理程序运行错误_浅谈Python异常处理机制

    异常机制己经成为衡量一门编程语言是否成熟的标准之一,使用异常处理机制的 Python 程序有更好的容错性,更加健壮. 对于计算机程序而言,情况就更复杂了一一没有人能保证自己写的程序永远不会出辛苦!就算 ...

最新文章

  1. 思科交换机Debug调试命令
  2. AI公开课:19.02.20 雷鸣教授《人工智能革命与机遇》课堂笔记以及个人感悟
  3. Java面向对象(2) —— 继承
  4. 整合弹簧,速度和瓷砖
  5. cefsharp 加载网页慢_网站访问慢的排查方案(史上最详细)
  6. java装箱和拆箱的意义_java的自动拆箱和装箱是每个程序员都要知道的
  7. 光驱是DVD,而系统却显示为CD驱动器的原因
  8. 调用百度“搜索建议(BaiduSuggestion)”的 API
  9. 学excel还是学python_以Excel处理为目的学习python还是VBA?
  10. 【EDM邮件营销】独立站卖家如何通过用户标签提高EDM邮件打开率
  11. JS基础学习--第一周
  12. 美团点评前端面试小结
  13. 计算机专业电脑i5与i7的区别,电脑i5处理器和i7处理器有什么区别
  14. epub与txt的区别是什么?有什么好用的epub阅读器
  15. 【BYM】Android 实现相机快门动画,android音视频何俊林
  16. 2022年互联网行业薪酬趋势报告
  17. 青山清水静心情 下联是...
  18. Matlab:创建、串联和扩展矩阵
  19. Opencv读取网络摄像头的rtsp流
  20. 2020-8-25 吴恩达DL学习-C4 卷积神经网络-第二周 CNN实例探究(2.7Inception 网络)

热门文章

  1. 树莓派 安装中文字体、中文输入法fcitx和googlepinyin输入法
  2. android 单选框 icon,Android中的普通对话框、单选对话框、多选对话框、带Icon的对话框、以及自定义Adapter和自定义View对话框详解...
  3. powertoys中文版
  4. altair feko+winprop 2020中文版
  5. bobo老师机器学习笔记1.1 - 什么是机器学习
  6. Spring boot AOP 实现Redis 存储
  7. 黑盒测试实践(小组作业)每日例会记录——11.27
  8. 两个input在一行让它们能对齐
  9. 小程序使用wxParse解析html
  10. android 蓝牙低耗能(LBE)技术介绍