У меня есть метод хранения в DocumentController. Этот метод использует специальный FormRequest laravel для проверки данных запроса. Блок try catch в этом методе хранилища должен обрабатывать исключение ValidationException, отправляя пользовательское сообщение JSON вместе с ошибками.
DocumentController.php
public function store(DocumentStoreRequest $req) // controller
{
try
{
$validData = $req->validated();
$path = $this->storeImage($req->file('document_file'));
$validData['doc_path'] = $path;
unset($validData['document_file']);
Document::create($validData);
return response()->json([
"message"=>"Add document for citizen $validData[nik] is success",
"data"=>$validData
], 201);
}
catch(ValidationException $e) // Should handle the ValidationException
{
return response()->json([
"message"=>"Validation error",
"errors"=>$e->errors()
], 422);
}
catch(\Exception $e)
{
return response()->json([
'message' => "Interval Server Error : \n".$e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine(),
'trace' => $e->getTrace(),
], 500);
}
}
private function storeImage($file)
{
$file_name = time() . '-' . uniqid() . '.' . $file->getClientOriginalExtension();
$path = "public/images";
$file_path = $file->storeAs($path, $file_name);
return $file_path;
}
DocumentStoreRequest.php
public function rules(): array // FormRequest
{
return [
"citizen_id"=>["required", "exists:citizens,id"],
"document_file"=>["required", "image:png"],
"type_id"=>["required", new OnlyOneTypeOfDocument($this->citizen_id)]
];
}
OnlyOneTypeOfDocument.php
private $citizen;
public function __construct($citizen_id)
{
$this->citizen = Citizen::find($citizen_id);
}
public function validate(string $attribute, mixed $value, Closure $fail): void // custom validation rule
{
if($this->citizen==null) return;
$document=$this->citizen->documents->where("id", "!=", $value);
if($document->count() > 0) // fail the validation if citizen already have a document with the same type
{
$type_name = $document->first()->documentType->name;
$nik = $this->citizen->nik;
$fail("The document with type of ".$type_name." already exists for citizen ".$nik);
}
}
Проблема в том, что встроенный в laravel класс-обработчик мешает процессу и перехватывает исключение ValidationException до того, как оно сможет быть обработано блоком try catch в методе хранилища. >
Я хочу отключить эту «обработку ValidationException по умолчанию». Я пытался изменить файл handler.php и файл app.php в папке начальной загрузки, но ни один из них не дал мне правильного решения моей проблемы.
Ответ по умолчанию
{
"message": "The document file field is required. (and 1 more error)",
"errors": {
"document_file": [
"The document file field is required."
],
"type_id": [
"The document with type of Kartu Keluarga already exists for citizen 3201010101010002"
]
}
}
Желаемый ответ
{
"message": "Validation Error",
"errors": {
"document_file": [
"The document file field is required."
],
"type_id": [
"The document with type of Kartu Keluarga already exists for citizen 3201010101010002"
]
}
}
Подробнее здесь: https://stackoverflow.com/questions/792 ... on-handler
Как отключить обработчик ValidationException по умолчанию? [дубликат] ⇐ Php
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Проблема с запросом DELETE в API Node.js/DynamoDB — ValidationException
Anonymous » » в форуме Javascript - 0 Ответы
- 13 Просмотры
-
Последнее сообщение Anonymous
-