【发布时间】:2017-03-20 06:23:38
【问题描述】:
我正在尝试在我的 Lumen API 中包含验证,但是当验证失败时我在响应时遇到了一些困难:
BooksController.php
public function store(Request $request)
{
$this->validateBook($request);
$book = Book::create($request->all());
$data = $this->item($book, new BookTransformer());
return response()->json($data, 201, [
'Location' => route('books.show', ['id' => $book->id]),
]);
}
private function validateBook(Request $request)
{
$this->validate($request, [
'title' => 'required|max:255',
'description' => 'required',
'author_id' => 'required|exists:authors,id',
], [
'description.required' => 'Please fill out the description.',
]);
}
我已修改我的处理程序以检查 ValidationException 的实例,但无论出于何种原因,我的响应始终相同...
Handler.php
public function render($request, Exception $e)
{
if ($request->wantsJson()) {
$response = [
'message' => (string) $e->getMessage(),
'status' => 400,
];
if ($e instanceof HttpException) {
$response['message'] = Response::$statusTexts[$e->getStatusCode()];
$response['status'] = $e->getStatusCode();
} else if ($e instanceof ModelNotFoundException) {
$response['message'] = Response::$statusTexts[Response::HTTP_NOT_FOUND];
$response['status'] = Response::HTTP_NOT_FOUND;
} else if ($e instanceof ValidationException) {
// [BUG] Shouldn't this display the fields that have failed?
$response['message'] = 'how do I display what fields failed?';
$response['status'] = Response::HTTP_UNPROCESSABLE_ENTITY;
}
if ($this->isDebugMode()) {
$response['debug'] = [
'exception' => get_class($e),
'trace' => $e->getTrace(),
];
}
return response()->json(['error' => $response], $response['status']);
}
return parent::render($request, $e);
}
如果我删除检查 an 而不是 ValidationException 的代码块,我的响应总是相同的:
{
"error": {
"message": "The given data failed to pass validation.",
"status": 400
}
}
但是,对于客户端尝试与 API 交互的任何人来说,这将是一场噩梦,因为它没有指定有关哪些字段失败并且不包含我的自定义错误消息的任何信息。
我期待的更像是:
{
"error": {
"message": "The given data failed to pass validation.",
"errors": {
"title": "The title is required.",
"description": "Please fill out the description."
},
"status": 422
}
}
我做错了什么?我怎样才能做到这一点?
【问题讨论】: