Better API response when request body is not valid JSON (references #126)

This commit is contained in:
Bernd Bestel 2019-01-05 20:39:22 +01:00
parent c042657dd8
commit f6cf26009d
No known key found for this signature in database
GPG Key ID: 71BD34C0D4891300
2 changed files with 41 additions and 8 deletions

View File

@ -32,10 +32,24 @@ class GenericEntityApiController extends BaseApiController
{ {
if ($this->IsValidEntity($args['entity'])) if ($this->IsValidEntity($args['entity']))
{ {
$newRow = $this->Database->{$args['entity']}()->createRow($request->getParsedBody()); $requestBody = $request->getParsedBody();
$newRow->save();
$success = $newRow->isClean(); try
return $this->ApiResponse(array('success' => $success)); {
if ($requestBody === null)
{
throw new \Exception('Request body could not be parsed (probably invalid JSON format or missing/wrong Content-Type header)');
}
$newRow = $this->Database->{$args['entity']}()->createRow($requestBody);
$newRow->save();
$success = $newRow->isClean();
return $this->ApiResponse(array('success' => $success));
}
catch (\Exception $ex)
{
return $this->VoidApiActionResponse($response, false, 400, $ex->getMessage());
}
} }
else else
{ {
@ -47,10 +61,24 @@ class GenericEntityApiController extends BaseApiController
{ {
if ($this->IsValidEntity($args['entity'])) if ($this->IsValidEntity($args['entity']))
{ {
$row = $this->Database->{$args['entity']}($args['objectId']); $requestBody = $request->getParsedBody();
$row->update($request->getParsedBody());
$success = $row->isClean(); try
return $this->ApiResponse(array('success' => $success)); {
if ($requestBody === null)
{
throw new \Exception('Request body could not be parsed (probably invalid JSON format or missing/wrong Content-Type header)');
}
$row = $this->Database->{$args['entity']}($args['objectId']);
$row->update($requestBody);
$success = $row->isClean();
return $this->ApiResponse(array('success' => $success));
}
catch (\Exception $ex)
{
return $this->VoidApiActionResponse($response, false, 400, $ex->getMessage());
}
} }
else else
{ {

View File

@ -32,6 +32,11 @@ class UsersApiController extends BaseApiController
try try
{ {
if ($requestBody === null)
{
throw new \Exception('Request body could not be parsed (probably invalid JSON format or missing/wrong Content-Type header)');
}
$this->UsersService->CreateUser($requestBody['username'], $requestBody['first_name'], $requestBody['last_name'], $requestBody['password']); $this->UsersService->CreateUser($requestBody['username'], $requestBody['first_name'], $requestBody['last_name'], $requestBody['password']);
return $this->ApiResponse(array('success' => true)); return $this->ApiResponse(array('success' => true));
} }