1 Star 0 Fork 10

molpage / Discuz-Q-Docs

forked from Discuz / Discuz-Q-Docs 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
api异常处理.md 1.54 KB
一键复制 编辑 原始数据 按行查看 历史
leiyu 提交于 2019-10-08 17:23 . 异常处理

api 异常处理

通常情况下PHP会抛出各种异常,或者自己定义的PHP 异常,也就是常用的 Exception,正常情况在如果程序不需要自定义异常返回的结果,可以直接忽略,如果某些异常需要自定义返回JSON返回相关信息,可以定义相关异常

  • 使用方法,实现 Tobscure\JsonApi\Exception\Handler\ExceptionHandlerInterface 该类,方法 manages 可判断当前是哪个异常报的错,handle 方法可以定义返回结果数据
<?php


namespace App\Api\Exceptions;


use Exception;
use Tobscure\JsonApi\Exception\Handler\ExceptionHandlerInterface;
use Tobscure\JsonApi\Exception\Handler\ResponseBag;

class NoExceptionHandler implements ExceptionHandlerInterface
{

    /**
     * If the exception handler is able to format a response for the provided exception,
     * then the implementation should return true.
     *
     * @param \Exception $e
     *
     * @return bool
     */
    public function manages(Exception $e)
    {
        // TODO: Implement manages() method.
        return $e instanceof RouteNotFoundException;;
    }

    /**
     * Handle the provided exception.
     *
     * @param \Exception $e
     *
     * @return \Tobscure\JsonApi\Exception\Handler\ResponseBag
     */
    public function handle(Exception $e)
    {
        // TODO: Implement handle() method.
        $status = 404;
        $error = [
            'status' => (string) $status,
            'code' => 'route_not_found'
        ];

        return new ResponseBag($status, [$error]);
    }
}
1
https://gitee.com/molpage/Discuz-Q-Docs.git
git@gitee.com:molpage/Discuz-Q-Docs.git
molpage
Discuz-Q-Docs
Discuz-Q-Docs
master

搜索帮助