Lumen开发:Lumen的异常处理机制
版权声明:本文为博主原创文章,未经博主允许不得转载。
Lumen的核心类Application引用了专门用于异常处理的RegistersExceptionHandlers,
1 2 3 4 | class Application extends Container { use Concerns\RoutesRequests, Concerns\RegistersExceptionHandlers; |
直接来看一下这个引用里的方法RegistersExceptionHandlers.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 | <?php namespace 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对异常处理做的默认绑定,这里的单例绑定是接口绑定类的类型
1 2 3 4 | $app ->singleton( Illuminate\Contracts\Debug\ExceptionHandler:: class , App\Exceptions\Handler:: class ); |
app/Exceptions/Handler.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | <?php namespace 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,这样,我们就可以很方便的做异常拦截和处理了!比如,
1 2 3 4 5 6 7 8 9 | 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
版权声明:本文为博主原创文章,未经博主允许不得转载。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· 因为Apifox不支持离线,我果断选择了Apipost!