tp5中捕获异常的配置
首选在配置文件中加入配置如下
// 异常处理handle类 留空使用 hinkexceptionHandle
"exception_handle" => "\app\common\exception\Http",
"http_exception_template" => [
// 定义404错误的重定向页面地址
404 => APP_PATH."view/error/404.html",
],
值得注意的是该配置文件必须是所有模块的而不是单个的模块的
目录结构图如下
然后在appcommonexceptionHttp.php文件中加入以下代码:
<?php
namespace appcommonexception;
use Exception;
use thinkexceptionHandle;
use thinkexceptionHttpException;
use thinkResponse;
class Http extends Handle
{
public function render(Exception $e)
{
// 参数验证错误
if ($e instanceof ValidateException) {
return json($e->getError(), 422);
}
// 请求异常
if ($e instanceof HttpException && request()->isAjax()) {
return response($e->getMessage(), $e->getStatusCode());
}
//TODO::开发者对异常的操作
if($e->getStatusCode()=="404"){
return response($e->getMessage(), $e->getStatusCode());
}
//可以在此交由系统处理
return parent::render($e);
}
}
然后就可以在编码中捕捉异常了
try{
Db::name("user")->find();
}catch(Exception $e){
$this->error("执行错误");
}
$this->success("执行成功!");