webman 异常处理类 的使用方法哪位能给一下

langbin

webman 异常处理类 的使用方法哪位能给一下
我添加了一个异常类但是调用,好像没有执行我自定义的异常类
求个使用的方法
我现在调用 是这样调的
throw new ApiException("发生错误",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
    {

         // 参数验证错误
         if ($exception instanceof ValidateException) {
            return json($exception->getError(), 422);
        }

        //下面是我加的抛出JSON 。
        if($exception instanceof ApiException){
            return json(['code'=>$exception->getCode(),'message'=>$exception->getMessage()]);
        }
        // 请求异常
        if ($exception instanceof HttpException && request()->isAjax()) {
            return response($exception->getMessage(), $exception->getStatusCode());
        }
        return parent::render($request, $exception);
    }

但是抛出的不是JSON
是需要怎么才能使用呢

4004 4 0
4个回答

喵了个咪
return [
    //'ApiException' => support\exception\ApiException::class,
    '' => support\exception\Handler::class,
];

你这个配置明显没启用你自定义的异常类啊

  • langbin 2021-10-19

    开始启用了。后来发现不行才去掉的

智佳思远

按照手册,你的配置不对吧,全局异常处理key用'',不能用ApiException才对。如果是多应用才会写具体的key,key就是对应的应用。

正确的配置应该是这样

return [
    '' => support\exception\ApiException::class,
];
  • 暂无评论
不败少龙
return [
    'api' => support\exception\ApiException::class,
];
  • 暂无评论
cainiao009

记录一下

config\exception.php

'' => support\exception\Handler::class

使用
use support\exception\BusinessException;

throw new BusinessException('haha',404);

返回如果不是json($request->expectsJson())
就在请求headers加入
accept:json

  • 暂无评论
年代过于久远,无法发表回答
🔝