我正在尝试在FOSRestBundle中添加自定义异常控件,但它似乎忽略了我的自定义消息(响应的状态代码没问题)。
我有:
throw new HttpException(404, "User {$id} not found");
但得到这个json的回应:
{
"error": {
"code": 404,
"message": "Not Found"
}
}
所以我找不到显示自定义消息的方法
您还可以使用以下配置抛出自己的异常:
fos_rest:
exception:
codes:
'My\Custom\NotFound\Exception404': 404
messages:
'My\Custom\NotFound\Exception404': true
在您自己的异常类中提供自定义消息,它应该按预期工作。
在View Layer documentation:If you don't like the default exception structure, you can provide your own implementation.
class ExceptionWrapperHandler implements ExceptionWrapperHandlerInterface
{
/**
* @param array $data
*
* @return array
*/
public function wrap($data)
{
// we get the original exception
$exception = $data['exception'];
// some operations
// ...
// return the array
return array(
'code' => $code,
'message' => $message,
'value' => $value
);
}
}
// config.yml
fos_rest:
view:
exception_wrapper_handler: Namespace\To\ExceptionWrapperHandler
要显示自定义异常消息(只需显示到app / config / config.yml):
fos_rest:
exception:
messages:
Symfony\Component\HttpKernel\Exception\HttpException: true