基于symfony搭建REST API(四)- 异常处理

在前面几节的基础上,我们来把代码再完善一下。

如果我们现在使用GET访问一个不存在的用户,比如/api/v1/users/99
接口不会返回任何东西,这肯定不是我们想要的结果。其实只要在适当的位置抛出异常就好了。

  1. 实体不存在
    /**
     * 获取用户信息
     *
     * @Rest\Get("/users/{userId}")
     * @return View
     */
    public function getAction(int $userId) :View
    {
        $user = $this->userService->getUser($userId);
        //not found exception
        if (!$user) {
            throw new EntityNotFoundException('资源不存在!');
        }
        return View::create($user, Response::HTTP_OK);
    }

这样接口返回了一个代码为500的错误信息,我们预期是要得到一个404返回信息,修改一下fos_rest.yaml配置文件

# /config/packages/fos_rest.yaml
    exception:
        exception_controller: 'fos_rest.exception.controller:showAction'
        codes:
            Doctrine\ORM\EntityNotFoundException: 404

刷新再次访问,返回了我们想要的结果:

{
    code: 404,
    message: "资源不存在!"
}
  1. 参数错误或其他逻辑错误
    一般在POST或PUT请求时,需要验证参数的合法性;我们可以在实体类中的setXxx方法中对参数进行检查,不合法的将抛出异常InvalidArgumentException
 // src/Entity/User.php

    /**
     * @param string $name
     * @return User
     * @throws InvalidArgumentException
     */
    public function setName(string $name): self
    {
        //$name必须是手机号
        if(!preg_match('/^1\d{10}$/', $name)) {
            throw new \InvalidArgumentException('手机号码格式不正确!');
        }
        $this->name = $name;

        return $this;
    }

当调用添加用户接口时,返回的是

{
    code: 500,
    message: "手机号码格式不正确!"
}

这并不是我们想要的结果,需要把code改成400,再来修改下fos_rest.yaml文件

# Read the documentation: https://symfony.com/doc/master/bundles/FOSRestBundle/index.html
fos_rest:
    view:
        view_response_listener:  true
    exception:
        exception_controller: 'fos_rest.exception.controller:showAction'
        codes:
            Doctrine\ORM\EntityNotFoundException: 404
            \LogicException: 400
            \DomainException: 400
        messages:
            Doctrine\ORM\EntityNotFoundException: true
            \LogicException: false
            \DomainException: false
    format_listener:
        rules:
            - { path: ^/api, prefer_extension: true, fallback_format: json, priorities: [ json] }
            - { path: ^/, fallback_format: html }

把LogicException和DomainException都设置成400错误即可,其他自定义也可以用这种方法来添加。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,273评论 19 139
  • 一说到REST,我想大家的第一反应就是“啊,就是那种前后台通信方式。”但是在要求详细讲述它所提出的各个约束,以及如...
    时待吾阅读 3,501评论 0 19
  • 人的一生大多都是平凡的啊。 没那么多所谓的挣扎。人有一种“比惨”的心理,总觉得自己是世界上最惨的人,这不...
    初简简阅读 196评论 0 0
  • 寻你,于花开的瞬间 你的笑颜 宛如花儿绽放 似骄阳般绚烂 花落无声 而你的眉眼 笼罩着氤氲的愁雾 却从此潜入了我的...
    温景婧Jane阅读 314评论 0 1
  • 有种不言而喻的孤独 跳脱了世俗 有种似是而非的触觉 洗礼了日风 心脏跳动着的呼喊 原来,我又跳入了另一个
    Echo的石头部落阅读 124评论 0 0