美文网首页基于symfony搭建REST API
基于symfony搭建REST API(四)- 异常处理

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

作者: 又起风了_ | 来源:发表于2018-11-30 12:02 被阅读62次

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

如果我们现在使用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错误即可,其他自定义也可以用这种方法来添加。

相关文章

网友评论

    本文标题:基于symfony搭建REST API(四)- 异常处理

    本文链接:https://www.haomeiwen.com/subject/rlnccqtx.html