当前位置: 首页 > 后端技术 > PHP

HowtoDesignPHPExceptionsElegantly

时间:2023-03-29 18:17:39 PHP

PrefaceWhenIfirstcameintocontactwithPHP,Ididn’trealizetheimportanceofexceptions.Sometimesit’sdifficulttofindtheproblempointaccurately.Handlingexceptionscorrectlyisalsoakindofknowledge.了很多变动,异常类Exception和错误类Error都实现了Throwable接口结构如下:ThrowableErrorArithmeticErrorDivisionByZeroErrorAssertionErrorParseErrorTypeErrorArgumentCountErrorExceptionClosedGeneratorExceptionDOMExceptionErrorExceptionIntlExceptionLogicExceptionBadFunctionCallExceptionBadMethodCallExceptionDomainExceptionInvalidArgumentExceptionLengthExceptionOutOfRangeExceptionPharExceptionReflectionExceptionRuntimeExceptionOutOfBoundsExceptionOverflowExceptionPDOExceptionRangeExceptionUnderflowExceptionUnexpectedValueExceptionSodiumException什么时候才需要抛异常这个一切从实际出发,如果你觉得你的代码可能会出现问题,就可以进行抛出异常如何CatchexceptionsUsetry...catch...finallyinPHPtocatchexceptionspublicfunctiontest(){try{//codelogicthatmaygowrong}catch(\Exception$e){echo$e->getMessage();}finally{//todo}}Ifyouarenotsurewhetherthereisanexceptionoranerror,youcandirectlycatchtheThrowableexceptionpublicfunctiontest(){try{//codelogicthatmaygowrong}catch(\Throwable$e){echo$e->getMessage();}finally{//todo}}业务场景实战现在很多项目都是前后端分离,开发restful风格接口的设计。下面我在实战中使用tp5框架实战在如何优雅的使用异常的说明中,选择一个比较简单的业务场景。以登录模块为例。用户在移动端登录时,需要进行登录、注册、忘记密码、获取手机验证码等操作。构建约束条件登录输入参数:用户手机号、用户密码、手机验证码约束:用户手机号不能为空,格式正确,用户存在,密码不能为空,密码格式为正确,手机验证码不能为空,且为有效期内的注册入口:用户手机号、用户密码、密码。二次确认手机验证码。约束条件:用户手机号不能为空,格式正确,用户确实是新用户。为空,密码格式正确。第二个密码必须与密码相同。手机验证码不能为空且在有效期内。为空,格式正确,用户确实存在。密码不能为空。密码格式正确。第二个密码必须与密码相同。手机验证码不能为空且在有效期内。号码约束:用户手机号不能为空,格式正确。一分钟内只能获取一个自定义tp5异常。创建异常处理Handleclass#application\lib\exception\ExceptionHandlenamespaceapplication\lib\exception;useException;usethink\exception\Handle;classExceptionHandleextendsHandle{/***@var$httpStatusCodehttp状态码*/private$httpStatusCode;/***@var$msg错误信息*/private$msg;/***@var$code错误代码*/private$code;#自定义错误异常需要重写tp5父类的render方法publicfunctionrender(Exception$e){if($einstanceofBaseException){#自定义异常$this->httpStatusCode=$e->httpStatusCode;$this->msg=$e->msg;$this->code=$e->代码;}else{#系统异常//TODO记录错误日志returnparent::render($e)}$result=['code'=>$this->code,'msg'=>$this->msg];#返回给前端returnjson($result,$this->httpStatusCode);}创建一个基础异常类#application\lib\exception\BaseExceptionnamespaceapplication\lib\exception;usethink\Exception;#异常类需要继承tp5的异常基类classBaseExceptionextendsException{public$httpStatusCode=401;public$msg='参数错误';公共$代码=10000;公共函数__construct(array$params=[]){if(array_key_exists('httpStatusCode',$params)){$this->httpStatusCode=$params['httpStatusCode'];}if(array_key_exists('msg',$params)){$this->msg=$params['msg'];}if(array_key_exists('code',$params)){$this->code=$params['co德'];}}}创建具体的异常类参数错误异常类命名空间app\lib\exception;classParameterExceptionextendsBaseException{public$httpStatusCode=200;public$msg='参数错误';public$code=10000;}用户不存在classUserNotExistsExceptionextendsBaseException{public$httpStatusCode=200;public$msg='用户不存在';public$code=20000;}如何使用先来看看登录函数传统的处理方式publicfunctionlogin($phone,$password){$uid=$this->getUidByPhone($phone);if(!$uid){#process}}通过异常处理publicfunctionlogin($phone,$password){$uid=$this->getUidByPhone($phone);if(!$uid){#抛出异常返回前端thrownewUserNotExistsException();}}