1.配置config.php
自定义异常路径:
// 默认AJAX 数据返回格式,可选json xml ... 'default_ajax_return' => 'json',
'exception_handle' => '\\app\\exceptions\\ExceptionHandle',
2.
--------------------------------------------------------
<?php
namespace app\exceptions;
use think\exception\Handle;
/** * Class ExceptionHandle * 全局异常处理 * @package app\exceptions */ class ExceptionHandle extends Handle { /** * 渲染方式 * @param Exception $e * @return \think\Response */ public function render(\Exception $e) { if ($e instanceof \app\exceptions\Exception) { return json([ 'code' => $e->getCode(), 'message' => $e->getMessage() ], $e->getCode()); } return parent::render($e); } }
--------------------------------------------------------
3.
---------------------------------------------------------
<?php
namespace app\exceptions;
use \Throwable;
/** * Class Exception * 异常基类 * @package app\exceptions */ class Exception extends \Exception { public function __construct(string $message = "", int $code = 0, Throwable $previous = null) { parent::__construct($message, $code, $previous); } }
4.
------------------------------------
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2018/6/19 * Time: 11:29 */
namespace app\ninty9api\exception;
use app\exceptions\Exception;
class UserException extends Exception { // HTTP 状态码 404,200 public $code = 400;
// 错误具体信息 public $msg = '参数错误';
// 自定义的错误码 public $errorCode = 10000;
/** * UserException constructor. * @param $message * @param int $code * @param null $throwable */ public function __construct($message, $code=0, $throwable=null) { if ( is_array($message)) { if (array_key_exists('code',$message)) { $this->code = $message['code']; }
if (array_key_exists('msg',$message)) { $this->msg = $message['msg']; }
if (array_key_exists('errorCode',$message)) { $this->errorCode = $message['errorCode']; } }
parent::__construct($message, $code, $throwable); }
} -------------------------------------------------
5.
------------------------------------------------
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2018/6/20 * Time: 10:37 */
namespace app\ninty9api\exception;
use Throwable;
class ParameterException extends UserException { public $code = 400; public $msg = '参数错误'; public $errorCode = 10000;
public function __construct(string $message = "", int $code = 0, Throwable $previous = null) { parent::__construct($message, $code, $previous); }
/** * @param int $code */ public function setCode(int $code) { $this->code = $code; }
/** * @param string $msg */ public function setMsg(string $msg) { $this->msg = $msg; }
/** * @param int $errorCode */ public function setErrorCode(int $errorCode) { $this->errorCode = $errorCode; } } -------------------------------
------------------------------------------------
|