记录日志ExceptionHandle.php
1 <?php 2 3 namespace app; 4 5 use app\admin\AuthErrorException; 6 use app\admin\ErrorException; 7 use app\home\NotFoundException; 8 use app\model\SystemSetting; 9 use think\db\exception\DataNotFoundException; 10 use think\db\exception\ModelNotFoundException; 11 use think\exception\Handle; 12 use think\exception\HttpException; 13 use think\exception\HttpResponseException; 14 use think\exception\ValidateException; 15 use think\Response; 16 use Throwable; 17 use think\facade\Log; 18 19 /** 20 * 应用异常处理类 21 */ 22 class ExceptionHandle extends Handle 23 { 24 /** 25 * 不需要记录信息(日志)的异常类列表 26 * @var array 27 */ 28 protected $ignoreReport = [ 29 HttpException::class, 30 HttpResponseException::class, 31 ModelNotFoundException::class, 32 DataNotFoundException::class, 33 ValidateException::class, 34 ]; 35 36 /** 37 * 记录异常信息(包括日志或者其它方式记录) 38 * 39 * @access public 40 * @param Throwable $exception 41 * @return void 42 */ 43 public function report(Throwable $e): void 44 { 45 // 使用内置的方式记录异常日志 46 parent::report($e); 47 Log::write(request()->url() . '|' . $e->getMessage(), 'error'); 48 } 49 50 /** 51 * Render an exception into an HTTP response. 52 * 53 * @access public 54 * @param \think\Request $request 55 * @param Throwable $e 56 * @return Response 57 */ 58 public function render($request, Throwable $e): Response 59 { 60 $appName = app('http')->getName(); 61 62 # 表单验证 63 if ($e instanceof ValidateException) { 64 return JsonMessage($e->getError()); 65 } 66 67 # 手动抛出的json异常 68 if ($e instanceof ErrorException) { 69 return JsonMessage($e->getCode() . '#' . $e->getMessage(), $e->getStatusCode()); 70 } 71 72 # 手动抛出的404页面, 后台 73 if ($e instanceof AuthErrorException && $appName == 'admin') { 74 if ($request->isAjax()) { 75 return JsonError($e->getCode() . '#' . $e->getMessage()); 76 } 77 return view('/404', ['content' => $e->getMessage()]); 78 } 79 80 # 手动抛出的404页面, 前台 81 if (($e instanceof NotFoundException || $e instanceof HttpException || $e instanceof \think\exception\ErrorException) && $appName == 'home') { 82 if ($request->isAjax()) { 83 return JsonError($e->getCode() . '#' . $e->getMessage()); 84 } 85 $this->app->view->layout(false); 86 //获取模板目录 87 $template = SystemSetting('site.site_template'); 88 $template = !empty($template) ? $template : 'default'; 89 return view($template . '/404', ['content' => $e->getMessage()]); 90 } 91 92 // 其他错误交给系统处理 93 return parent::render($request, $e); 94 } 95 }
作者:糖粿
来源:博客园
转载请注明原文链接:https://www.cnblogs.com/silen0119/p/16139152.html
声援博主: 如果您觉得文章对您有帮助,可以点击文章右下角【推荐】一下。