巅云php学苑
近期车展
最新发布
快速导航

thinkphp5.1 中使用自定义异常处理类进行接管

操作系统 / linux / 2022-04-03 22:06
visits visits 451 collect - report - QRcode

Basicinformation

content

配置文件修改

config/app.php
自定义异常接管类出处
"exception_handle" => ‘appcommonexceptionExceptionHandle",

自定义处理异常方法
寡人的存放目录为 app/common/exception

ApiException.php

namespace appcommonexception;
use Exception;
class ApiException extends Exception
{	
	/**
	 * 构造函数
	 */
	public function __construct(array $ApiErrConst, Throwable $previous = null)
	{
		$code = $ApiErrConst[0];
		$message = $ApiErrConst[1];	
		parent::__construct($message, $code, $previous);
	}
}

ExceptionHandle.php

namespace appcommonexception;
use Exception;
use thinkexceptionHandle;
use appcommonexceptionApiException;
use appcommonerrApiErrCode;
class ExceptionHandle extends Handle
{
	// 引入复用模块:JSON返回格式
	use appcommontraitsResponseJson; 
	public function render(Exception $e)
	{		
		if($e instanceof ApiException) {
			$code = $e->getCode();
			$message = $e->getMessage();	
		}else{
			$code = $e->getCode();
			if(!$code || $code < 0) {
				$code = ApiErrCode::ERROR_UNKNOW[0];
			}
			$message = $e->getMessage() ? $e->getMessage() : ApiErrCode::ERROR_UNKNOW[1];
		}		
		echo $this->jsonErrorData($code,$message); //该方法在下方
		// 其他错误交给系统处理
       // return parent::render($e); 
	}
}

错误码文件

存放目录:app/common/err

namespace appcommonerr;
class ApiErrCode 
{
	/** 
	 * API通用错误码 const 定义常量
	 * error_code < 1000
	 */	
    const ERROR_UNKNOW = [0, "未知错误"];
    const ERROR_URL = [1, "接口不存在"];
    .......
}

复用模块

针对API接口返回格式
存放目录:app/common/traits

namespace appcommontraits;
trait ResponseJson
{
	/**
	 * API接口出现业务异常时时返回
	 * @author Leo 
	 */
	public function jsonErrorData($code,$message,$data = [])
	{
		return $this->jsonResponse($code, $message, $data);
	}

	/**
	 * API接口请求成功时返回
	 * @author Leo 
	 */
	public function jsonSuccessData($data = [])
	{
		return $this->jsonResponse(200, "Sucess", $data);
	}

	/**
	 * 返回一个JSON
	 * @author Leo 
	 */
	private function jsonResponse($code,$message,$data) 
	{
		$content = [
			"code" => $code,
			"msg" => $message,
			"data" => $data
		];
		return json_encode($content);
	}
}

页面调用

// 文件头部引入
use appcommonexceptionApiException;
use appcommonerrApiErrCode;
// 引入复用模块:JSON返回格式
use appcommontraitsResponseJson;

// 示例
public function index() {
	throw new ApiException(ApiErrCode::ERROR_URL);		// 自定义异常抛出
}

到此这篇关于thinkphp5.1 中使用自定义异常处理类进行接管的文章就介绍到这了,更多相关thinkphp5.1 自定义异常处理类内容请搜索IT博客社区以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT博客社区!

notmore

Users comments(0)

rate100%
  • notmore
+ more
  • contacts:
  • area:
  • tel: total(2007)twigs area:unknown

联系我们

合作或咨询可通过如下方式:

QQ/微信:123456

网址:www.xxxx.cn

微信公众号:车展门票

关于本站

「车展网www.xxxxxxx.cn」是一个集全国各地品牌经销车商的平台,让您在所在城市,第一时间收到车展的最新消息,让您的试驾、选车、购车、贷车一步到位,更多优惠直达客户,无需东奔西走,带上中意的车回家,让您省钱,更省心。

Copyright 车展网 www.xxxx.cn Reserved渝ICP备xxxxxxxx号

关注我们