让你的错误信息更适合摸鱼的你
最近摸鱼的我想给对象写个求职简历,但是不会写css
,感觉这个东西巨难学,人都要裂开了!
但是看到PHP8
的注解
感觉美滋滋啊,在加上之前用hyperf
的Constant
, 感觉这个东西拿新特性写一下就当是摸鱼了。。 改进空间很多,自行脑补吧。
贴一下效果图
贴一下code
throw new \App\Exceptions\ExampleException(\App\Exceptions\ExampleException::PASSWORD_IS_ERROR);
- 下面就是营销号常用套路了。三个函数让前端为了理想(生存)花了十八块
文件路径: 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 协议》,转载必须注明作者和本文链接
摸的漂亮!
漂亮
生命不息,摸鱼不止!
低情商:摸鱼
高情商:公司技术能力再上一个台阶