1.配置config.phpphp
自定義異常路徑:ajax
// 默認AJAX 數據返回格式,可選json xml ...
'default_ajax_return' => 'json',
'exception_handle' => '\\app\\exceptions\\ExceptionHandle',
2.json
--------------------------------------------------------api
<?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);
}
}
--------------------------------------------------------app
3.this
---------------------------------------------------------spa
<?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.code
------------------------------------orm
<?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.xml
------------------------------------------------
<?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;
}
}
-------------------------------
------------------------------------------------