简体   繁体   中英

Symfony2 FOSRestBundle ParamFetcher JSON error

I have a Symfony2 setup with FOSRestBundle and I'm using the ParamFetcher.

I now have a route which has some requirements for it's parameters and I'd like to show a the error messages to the API-user, but in my current setup the error messages are not shown in production and in development they are way to extensive.

Parameter requirements

offset
Requirement \d+
Description Result offset
Default 0

limit
Requirement \d+
Description Result limit count
Default 100

Annotations:

/**
 * 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
 */

Making the request in production mode:

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"
  }
}

I already tried adding error_message to the Param rule, but that does not lead to a nice error message.

What should I do get a nice error message for the API end user?

We are doing it by implementing the ExceptionWrapperHandlerInterface, see eg 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);
}
}

You'll have access to lot's of information in $data. Check what you get for your param validation exception.

We're not using the annotation param validation but by extending the ExceptionWrapper we can eg easily achieve something like that in our code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM