写代码时,错误处理是必须的,可是方法各类各样,也各有优缺点php
c语言中固然就是返回码了,额外有系统级的错误码errno
错误码有个麻烦的地方,就是须要写大量的if判断。
GO语言中能够一次返回多个错误码框架
正常代码和错误处理分开,很干净,我的很是喜欢抛异常的方式。 ThinkPHP 项目中通常我会定义一个自定义的异常类ResException.phpthis
use think\Exception; class ResException extends Exception { private $response; public function __construct($code, $message='') { parent::__construct($message, $code); $this->response = new Response($code,$message); } public function getResponse() { return $this->response; } }
用框架全局的异常捕获类ExceptionHandle统一捕获ResException,这样在我们的控制层,逻辑层均可以方便的抛出。code
注意:抛异常应该表示程序发成错误,是少数发生的。get