У меня есть метод хранения в 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
Кемеровские программисты php общаются здесь
1733944976
Anonymous
У меня есть метод хранения в DocumentController. Этот метод использует специальный FormRequest laravel для проверки данных запроса. Блок try catch в этом методе хранилища должен обрабатывать исключение ValidationException, отправляя пользовательское сообщение JSON вместе с ошибками.
[b]DocumentController.php[/b]
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;
}
[b]DocumentStoreRequest.php[/b]
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)]
];
}
[b]OnlyOneTypeOfDocument.php[/b]
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 в папке начальной загрузки, но ни один из них не дал мне правильного решения моей проблемы.
[b]Ответ по умолчанию
{
"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"
]
}
}
Желаемый ответ[/b]
{
"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"
]
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79272940/how-to-disable-default-validationexception-handler[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия