Lumen开发:Lumen的异常处理机制
版权声明:本文为博主原创文章,未经博主允许不得转载。
Lumen的核心类Application引用了专门用于异常处理的RegistersExceptionHandlers,
class Application extends Container
{
use Concerns\RoutesRequests,
Concerns\RegistersExceptionHandlers;
直接来看一下这个引用里的方法RegistersExceptionHandlers.php
<?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对异常处理做的默认绑定,这里的单例绑定是接口绑定类的类型
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\Handler::class
);
app/Exceptions/Handler.php
<?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,这样,我们就可以很方便的做异常拦截和处理了!比如,
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
版权声明:本文为博主原创文章,未经博主允许不得转载。
Lumen开发:Lumen的异常处理机制的更多相关文章
- Lumen开发:添加手机验证,中文验证与Validator验证的“半个”生命周期
版权声明:本文为博主原创文章,未经博主允许不得转载. 添加手机验证方法可直接看这里:https://www.cnblogs.com/cxscode/p/9609828.html 今天来讲一下,Lume ...
- Lumen开发:结合Redis实现消息队列(1)
1.简介 Lumen队列服务为各种不同的后台队列提供了统一的API.队列允许你推迟耗时任务(例如发送邮件)的执行,从而大幅提高web请求速度. 1.1 配置 .env文件的QUEUE_DRIVER选项 ...
- 深入理解java异常处理机制
异常指不期而至的各种状况,如:文件找不到.网络连接失败.非法参数等.异常是一个事件,它发生在程序运行期间,干扰了正常的指令流程.Java通 过API中Throwable类的众多子类描述各种不同的 ...
- Java之异常处理机制
来源:深入理解java异常处理机制 2.Java异常 异常指不期而至的各种状况,如:文件找不到.网络连接失败.非法参数等.异常是一个事件,它发生在程序运行期间,干扰了正常的指令流程.Java通 ...
- SpringMVC异常处理机制详解[附带源码分析]
目录 前言 重要接口和类介绍 HandlerExceptionResolver接口 AbstractHandlerExceptionResolver抽象类 AbstractHandlerMethodE ...
- Java 异常处理机制和集合框架
一.实验目的 掌握面向对象程序设计技术 二.实验环境 1.微型计算机一台 2.WINDOWS操作系统,Java SDK,Eclipse开发环境 三.实验内容 1.Java异常处理机制涉及5个关键字:t ...
- ASP.NET(C#)中的try catch异常处理机制
在开发一个Umbraco平台系统的过程中,遇到了问题. 写的代码如下 fileUrl = MediaHelper.GetMediaUrl(Convert.ToInt32(publishedConten ...
- java异常处理机制 (转载)
java异常处理机制 本文来自:曹胜欢博客专栏.转载请注明出处:http://blog.csdn.net/csh624366188 异常处理是程序设计中一个非常重要的方面,也是程序设计的一大难点,从C ...
- 深入理解java的异常处理机制
JAVA异常的概念 异常指不期而至的各种状况,如:文件找不到.网络连接失败.非法参数等.异常是一个事件,它发生在程序运行期间,干扰了正常的指令流程.Java通 过API中Throwable类的 ...
- php错误处理和php异常处理机制
php错误处理 当我们开发程序时,有时候程序出现了问题,我们就可以用以下几种办法找出错误. 开发阶段:开发时输出所有的错误报告,有利于我们进行程序调试 运行阶段:我们不要让程序输出任何一种错误报 ...
随机推荐
- kubernetes1.5.2集群部署过程--非安全模式
运行环境 宿主机:CentOS7 7.3.1611 关闭selinux etcd 3.1.9 flunnel 0.7.1 docker 1.12.6 kubernetes 1.5.2 安装软件 yum ...
- [置顶]
kubernetes--Init Container
概念 Init Container就是做初始化工作的容器.可以有一个或多个,如果有多个,这些 Init Container 按照定义的顺序依次执行,只有所有的InitContainer 执行完后,主容 ...
- C和C++中函数运行时间测试
//clock()函数为c中,捕捉从程序开始运行到clock运行的时间//时间单位为clock tick,即为时钟打点#include<iostream>#include<cmath ...
- 用js怎么控制submit提交表单
需求: 1. 要在点击submit按钮的时候,弹出一个询问框,"你确定要修改?".如果按了"确定"那么就提交表单,否则就保留在原页面,既不提交不跳转. 2. 要 ...
- Nginx user_agent、if指令及全局变量
Nginx user_agent.if指令及全局变量 1.User_agent User Agent中文名为用户代理,简称 UA,它是一个特殊字符串头,使得服务器能够识别客户使用的操作系统及版本.CP ...
- Linux服务器大量向外发包问题排查
最近Linux redhat 6.5 APP 业务系统,向外大量发送流量,不断建立tcp连接,目标地址是美国的一个IP,估计被当成肉鸡了,比较悲惨,直接飞向IDC机房,防火墙显示这个APP服务器tcp ...
- C++11之右值引用(一):从左值右值到右值引用
C++98中规定了左值和右值的概念,但是一般程序员不需要理解的过于深入,因为对于C++98,左值和右值的划分一般用处不大,但是到了C++11,它的重要性开始显现出来. C++98标准明确规定: 左值是 ...
- CHM乱码解决方案!
--希望对您有所帮助,闲暇之余请访问我的网店高清数据线 下载了一个日文的chm帮助文件,打开的时候,发现是乱码, CHM 文档不像IE浏览器一样,右键可以选择字符编码,非常不便. 原因可能是 CHM ...
- mybatis学习笔记(10)-一对一查询
mybatis学习笔记(10)-一对一查询 标签: mybatis mybatis学习笔记10-一对一查询 resultType实现 resultMap实现 resultType和resultMap实 ...
- 隔行换色table
<style type="text/css"> table { margin: 0 auto; width: 600px; } table { border: 1px ...