异常处理
新版推荐使用异常处理的方式来返回错误,这样无需在代码逻辑里面使用太多的数据判断。
系统内置的异常处理类会在抛出异常后进行自动捕获并记录错误日志,出于日志存储空间考虑,有一些异常是被忽略的,并不会记录日志,例如HttpException、HttpResponseException及ValidateException异常等等,异常处理类通过render方法把异常信息转换为Response对象输出,如果是一个JSON请求则会自动使用JsonResponse输出,否则使用普通的Response对象输出。
你可以自定义异常处理类,重新定义render方法来进行异常信息的渲染输出。
默认安装后,自带了一个app\ExceptionHandle异常处理类,可以用于应用的自定义异常处理。
namespace app;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\Response;
use Throwable;
/**
-
应用异常处理类
*/
class ExceptionHandle extends Handle
{
/**- 不需要记录信息(日志)的异常类列表
- @var array
*/
protected $ignoreReport = [
HttpException::class,
HttpResponseException::class,
ModelNotFoundException::class,
DataNotFoundException::class,
ValidateException::class,
];
/**
- 记录异常信息(包括日志或者其它方式记录)
- @access public
- @param Throwable $exception
- @return void
*/
public function report(Throwable $exception): void
{
// 使用内置的方式记录异常日志
parent::report($exception);
}
/**
- Render an exception into an HTTP response.
- @access public
- @param \think\Request $request
- @param Throwable $e
-
@return Response
*/
public function render($request, Throwable $e): Response
{
// 添加自定义异常处理机制// 其他错误交给系统处理
return parent::render($request, $e);
}
}
该异常处理类不支持命令行下执行的情况,仅支持HTTP应用的异常处理。
think-whoops
可以支持使用Whoops接管异常, Whoops提供stackbased错误捕获及超美观的错误。需要安装扩展
composer require xiaodi/think-whoops
开启调试模式才正常接管, 关闭默认转交ThinkPHP处理config/whoops.php
<?php
return [
'enable' = true
];
帮助您从异常堆栈跟踪中打开代码编辑器,支持的编辑器包括
sublime
textmate
emacs
macvim
phpstorm
idea
vscode
atom
espresso
config/whoops.php
<?php
return [
'editor' = 'vscode'
];
使用效果
发表评论