让你的错误信息更适合摸鱼的你

最近摸鱼的我想给对象写个求职简历,但是不会写css ,感觉这个东西巨难学,人都要裂开了!
但是看到PHP8注解感觉美滋滋啊,在加上之前用hyperfConstant, 感觉这个东西拿新特性写一下就当是摸鱼了。。 改进空间很多,自行脑补吧。

  1. 贴一下效果图
    让你的错误信息更适合摸鱼的你

  2. 贴一下code
    throw new \App\Exceptions\ExampleException(\App\Exceptions\ExampleException::PASSWORD_IS_ERROR);

让你的错误信息更适合摸鱼的你

让你的错误信息更适合摸鱼的你

  1. 下面就是营销号常用套路了。三个函数让前端为了理想(生存)花了十八块
    文件路径: app/Exceptions/Handler.php
    增加内容
     public function render($request, Throwable $e)
     {
         // it is an error code,bacause i can't make constant value to string, also sometimes the error message will be Chinese, so I think it is a better way
         $error_code = $e->getMessage();
         $reflection_class = new \ReflectionClass($e);
         $reflection_class_constants_by_error_code = array_flip($reflection_class->getConstants());
         $exception_constant = $reflection_class_constants_by_error_code[$error_code] ?? null;
         $reflection_constant = $reflection_class->getReflectionConstant($exception_constant);
         $attribute_class_instance = $reflection_constant->getAttributes(ExceptionAttribute::class)[0]->newInstance();
         return $this->response($error_code, $attribute_class_instance->value, $this->getHttpCodeFromExceptionClass($e));
     }
     public function getHttpCodeFromExceptionClass(Throwable $e): int
     {
         if ($e instanceof \Illuminate\Validation\ValidationException) {
             return 422;
         }
         if ($e instanceof \Illuminate\Auth\AuthenticationException) {
             return 401;
         }
         if ($e instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) {
             return 404;
         }
         if ($e instanceof \Illuminate\Auth\Access\AuthorizationException) {
             return 403;
         }
         if ($e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) {
             return 404;
         }
         if ($e instanceof \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException) {
             return 405;
         }
         if ($e instanceof \Symfony\Component\HttpKernel\Exception\HttpException) {
             return $e->getStatusCode();
         }
         return 500;
     }
     public function response($error_code, $error_message, $status_code = 500)
     {
         return response()->json(['code' => $error_code, 'message' => $error_message], $status_code);
     }

    自己抽出来做成 trait

如果你需要 /** */ 类型的注解错误,请去看我之前发的一篇文章。这里不做赘述了,我也是菜鸡,你要批评我,我们就是菜鸡互啄 ~

让你的错误信息更适合摸鱼的你

本作品采用《CC 协议》,转载必须注明作者和本文链接
技术是要靠自己边学边整活儿才行的
陈先生
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 4
ojbkkk

摸的漂亮!

2年前 评论

生命不息,摸鱼不止!

1年前 评论

低情商:摸鱼

高情商:公司技术能力再上一个台阶

1年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!