簡體   English   中英

Symfony2 FOSRestBundle ParamFetcher JSON錯誤

[英]Symfony2 FOSRestBundle ParamFetcher JSON error

我有一個帶有FOSRestBundle的Symfony2設置,我正在使用ParamFetcher。

我現在有一條路線對它的參數有一些要求,我想向API用戶顯示錯誤信息,但在我目前的設置中,錯誤信息沒有顯示在生產和開發中,它們是廣泛的。

參數要求

offset
Requirement \d+
Description Result offset
Default 0

limit
Requirement \d+
Description Result limit count
Default 100

注釋:

/**
 * Get a list of users which can be limited to a certain result count and offset.
 *
 * Max 30 users per request allowed.
 *
 * @ApiDoc(
 *  resource=true,
 *  description="Load list of users",
 *  statusCodes={
 *      200="Returned when successful",
 *      400="Bad user input",
 *      500="In case of server error,"
 *  }
 * )
 *
 * @View()
 *
 * @param ParamFetcher $paramFetcher
 * @param int $offset integer offset (requires param_fetcher_listener: force)
 * @param int $limit integer result limit (requires param_fetcher_listener: force)
 * @QueryParam(name="offset", description="Result offset", default="0",
 *     requirements="\d+", strict=true, nullable=true)
 * @QueryParam(name="limit", description="Result limit count", default="30",
 *     requirements="\d+", strict=true, nullable=true)
 *
 * @return array response array
 */

在生產模式下發出請求:

Request URL
GET /events.json?offset=strangeText&limit=huh!?
Response Headers [Expand] 
400 Bad Request

Date: Tue, 02 Jun 2015 20:45:15 GMT
Server: Apache/2
X-Powered-By: PHP/5.5.25
Vary: User-Agent
Content-Type: application/json
Cache-Control: no-cache
Connection: close
Content-Length: 47
Response Body [Raw]
▿{
  "error": ▿{
    "code": 400,
    "message": "Bad Request"
  }
}

我已經嘗試將error_message添加到Param規則中,但這不會導致錯誤消息。

我應該怎么做為API最終用戶提供一個很好的錯誤消息?

我們通過實現ExceptionWrapperHandlerInterface來實現它,參見例如https://symfony.com/doc/current/bundles/FOSRestBundle/2-the-view-layer.html#forms-and-views

namespace My\Bundle\Handler;

class MyExceptionWrapperHandler implements ExceptionWrapperHandlerInterface
{
/**
 * {@inheritdoc}
 */
public function wrap($data)
{
    return new MyExceptionWrapper($data);
}
}

您可以訪問$ data中的大量信息。 檢查您的param驗證異常所得到的內容。

我們沒有使用注釋參數驗證,但通過擴展ExceptionWrapper,我們可以在代碼中輕松實現類似的功能:

throw new HttpException( 400, 'My custom message' );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM