webman 異常處理類 的使用方法哪位能給一下
我添加了一個(gè)異常類但是調(diào)用,好像沒有執(zhí)行我自定義的異常類
求個(gè)使用的方法
我現(xiàn)在調(diào)用 是這樣調(diào)的
throw new ApiException("發(fā)生錯(cuò)誤",100);
config/exception.php
return [
//'ApiException' => support\exception\ApiException::class,
'' => support\exception\Handler::class,
];
然后我在 support\exception\Handler中加入以下代碼
public function render(Request $request, Throwable $exception) : Response
{
// 參數(shù)驗(yàn)證錯(cuò)誤
if ($exception instanceof ValidateException) {
return json($exception->getError(), 422);
}
//下面是我加的拋出JSON 。
if($exception instanceof ApiException){
return json(['code'=>$exception->getCode(),'message'=>$exception->getMessage()]);
}
// 請(qǐng)求異常
if ($exception instanceof HttpException && request()->isAjax()) {
return response($exception->getMessage(), $exception->getStatusCode());
}
return parent::render($request, $exception);
}
但是拋出的不是JSON
是需要怎么才能使用呢
按照手冊(cè),你的配置不對(duì)吧,全局異常處理key用''
,不能用ApiException
才對(duì)。如果是多應(yīng)用才會(huì)寫具體的key,key就是對(duì)應(yīng)的應(yīng)用。
正確的配置應(yīng)該是這樣
return [
'' => support\exception\ApiException::class,
];
記錄一下
config\exception.php
'' => support\exception\Handler::class
使用
use support\exception\BusinessException;
throw new BusinessException('haha',404);
返回如果不是json($request->expectsJson())
就在請(qǐng)求headers加入
accept:json