# API接口中的异常处理
>[success]在API接口的开发过程中,使用TP自带的异常处理机制,可能并不能满足实际需求。
>TP默认是直接抛出异常,而API接口通常返回的是json数据格式。所以需要对异常类进行重写。
## 重写异常处理的`render`方法
### 重写异常处理类
~~~php
namespace app\common\lib\exception;
use think\exception\Handle;
class ApiExceptionHandle extends Handle
{
private $httpCode = 400;
public function render(\Exception $e)
{
if(config("app_debug")==true){
return parent::render($e);
}
if($e instanceof ApiException){
$this->httpCode = $e->httpCode;
}
$data = [
"code"=>0,
"msg"=>$e->getMessage(),
'data'=>[]
];
return json($data,$this->httpCode);
}
}
~~~
### 重写内部错误异常处理
~~~
namespace app\common\lib\exception;
use think\Exception;
class ApiException extends Exception
{
public $message="";
public $httpCode=500;
public $code=0;
public function __construct($message = '',$httpCode=0,$code=0)
{
$this->message = $message;
$this->httpCode = $httpCode;
$this->code =$code;
}
}
~~~
>[danger]重写异常类之后,需要在配置文件中,配置成自定义的异常类
~~~
// 异常处理handle类 留空使用 \think\exception\Handle
'exception_handle' => 'app\common\lib\exception\ApiExceptionHandle',
~~~