如何在 symfony5 中将所有 HttpExceptions 格式化为 json? [英] How to format all HttpExceptions as json in symfony5?

查看:53
本文介绍了如何在 symfony5 中将所有 HttpExceptions 格式化为 json?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 symfony5 控制器中,我可以通过以下方式返回 json 响应:

 return $this->json(['key' => 'content');

然而,当我抛出 HttpException 时,我在开发和生产中都看到了默认的 html 错误页面.

我想创建一个restful api,所以我想把所有的HttpExceptions转换成json.

我想配置我所有的控制器以将它们的响应格式化为 json.最多,我想添加一个异常处理程序,将异常转换为正确的消息.(在 prod 中它应该有更少的信息,在 dev 中它可能包含异常堆栈跟踪.)

我怎样才能做到这一点?我以为我可以使用 @Route 注释的 format 选项,但它不起作用.

这是我的示例控制器:

status = "OK";返回 $this->json($ok);}}

在寻找这个时,我遇到了:

composer 需要 symfony/serializer-pack

之后,我的异常呈现为 json 很好.

Within a symfony5 controller, I can return json responses via:

 return $this->json(['key' => 'content');

Yet when I throw an HttpException, I see the default html error page in both dev and production.

I want to create a restful api, so I want to convert all HttpExceptions into json.

I want to configure all my controllers to format their response as json. At most, I want to add one Exception handler that would transform the excpetions into proper messages. (In prod it should have less information, in dev it may contain the exception stacktrace.)

How can I achieve this? I thought I could use the format option of the @Route annotation but it doesn't work.

This is my example controller:

<?php declare(strict_types=1);

namespace App\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Annotation\Route;

class StatusController extends AbstractController
{
    /**
     * @Route("/status", name="status", format="json")
     * @Template
     * @return JsonResponse
     */
    public function status()
    {
        if (true) {
            // this will render as html, how to serialize it as json?
            throw new NotFoundHttpException("This is an example");
        }


        $ok = new \stdClass();
        $ok->status = "OK";

        return $this->json($ok);
    }
}

While looking for this I came across this PR which seems to achieve what I am trying to do, yet I am unsure what I am missing.

On the symfony blog I found following answer by Yonel Ceruto saying

you will need to install/enable the serializer component,

yet I have no idea what this entails.


In dev and prod I got these html views instead of a json response:

prod

dev

解决方案

Turns out all I was missing was installing the serializer-pack as pointed out in the symfony docs:

composer require symfony/serializer-pack

Afterwards, my exceptions render as json fine.

这篇关于如何在 symfony5 中将所有 HttpExceptions 格式化为 json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆