FOSRestBundle-使用异常处理程序中约束的错误消息

时间:2018-12-10 16:31:45

标签: symfony4 fosrestbundle

例如,我正努力从QueryParam中使用的约束传递消息:

class MyController extends FOSRestController
{
    /**
     * @param ParamFetcherInterface $paramFetcher
     * @return Response
     *
     * @Rest\Get("/reports/my_raport")
     * @Rest\QueryParam(name="filter", strict=true, requirements=@App\Validator\API\Constraints\Filter)
     */
    public function referralFoundsAccountUsage(ParamFetcherInterface $paramFetcher): Response
    {

        return new Response();
    }
}

我的fos_rest.yaml:

fos_rest:
  body_listener: true
  param_fetcher_listener:  true
  exception:
    enabled: true
    exception_controller: 'App\Controller\API\ExceptionController::showAction'
  format_listener:
    enabled: true
    rules:
    - { path: ^/api, prefer_extension: false, priorities: ['json'], fallback_format: json }

我想将约束返回的错误消息传递给ExceptionController,因此我可以将其格式化为json。

1 个答案:

答案 0 :(得分:0)

我找到了答案:

class ExceptionController extends FOSRestController
{
    public function showAction(Request $request, \Throwable $exception, DebugLoggerInterface $logger = null): Response
    {
        return new JsonApiResponse($exception->getMessage(), 400);
    }
}