1.thinkphp是很容易来写接口的,下面就来一个异常类的封装,首先我们需要在项目application里创建lib文件夹,如下图所示。

thinkphp5.1全局异常类封装_php

2.写BaseException的代码

<?php
namespace app\lib\exception;

use Exception;

class BaseException extends Exception
{
public $code=400;
public $msg='异常';
public $errorCode=999;

public function __construct($params=[]){
if(!is_array($params)) return;
if(array_key_exists('code', $params)) $this->code = $params['code'];
if(array_key_exists('msg', $params)) $this->msg = $params['msg'];
if(array_key_exists('errorCode', $params)) $this->errorCode = $params['errorCode'];
}
}

3.写ExceptionHandler的代码

<?php
namespace app\lib\exception;

use Exception;
use think\exception\Handle;

/**
* PHP异常处理类
*/
class ExceptionHandler extends Handle
{
public $code;
public $msg;
public $errorCode;

public function render(Exception $e)
{
if($e instanceof BaseException){
$this->code = $e->code;
$this->msg = $e->msg;
$this->errorCode = $e->errorCode;
}else{
//debug开启,显示默认异常
if(config('app.app_debug')) return parent::render($e);
$this->code = 500;
$this->msg = '服务器异常';
$this->errorCode = 999;
}
$res=[
'code'=>$this->code,
'msg'=>$this->msg,
'errorCode'=>$this->errorCode
];
return json($res,$this->code);
}
}

?>

4.接下来,我们引用,这里我是在Index.php中引用的,如下,代码

<?php

namespace app\Index\controller;

use think\Controller;
use think\Request;
use app\lib\exception\BaseException; // 这个就是引入我们的异常类

class Index extends Controller
{
/**
* 显示资源列表
*
* @return \think\Response
*/
public function index()
{
throw new BaseException(['msg'=>'验证失败']); // 上面的参数可以传也可以不传,不传的话就按默认
}
}

好了,这就是thinkphp5.1的异常类处理了。其他框架基本类同。如果还有其他需求可以参照
​​​官方异常处理文档​