Answer the question
In order to leave comments, you need to log in
How to customize response on bad request in REST API?
When accessing /api/web/v1/users/ using the GET method, a result about users is returned.
Can you please tell me how to give an adequate response with an error when calling this method via POST? Now I get the standard page "Page not found."
Answer the question
In order to leave comments, you need to log in
Error handling customization is described here www.yiiframework.com/doc-2.0/guide-rest-error-hand... .
Here is an example code (specified in the application api config):
'response' => [
'class' => 'yii\web\Response',
'format' => 'json',
'on beforeSend' => function ($event) {
$response = $event->sender;
if ($response->data !== null) {
$data = $response->data;
// Error handle
$error = '';
if( ! $response->isSuccessful) {
if(isset($data['message'])) {
$error = $data['message'];
} elseif(isset(current($data)['message'])) {
$error = current($data)['message'];
}
}
$response->data = [
'status' => $response->isSuccessful,
'code' => $response->statusCode,
'error' => $error,
];
if($response->isSuccessful) {
$response->data['data'] = $data;
}
// $response->statusCode = 200;
}
},
],
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question