Improve error reporting from API (#1194)

* apply API response across all requests

* apply API response across all requests
This commit is contained in:
David Bomba 2016-12-13 17:52:09 +11:00 committed by GitHub
parent f1fcc0b558
commit 0ceeefb10b
2 changed files with 29 additions and 24 deletions

View File

@ -1,9 +1,7 @@
<?php namespace App\Http\Requests;
use App\Libraries\Utils;
use App\Models\Invoice;
use Illuminate\Http\Request as InputRequest;
use Response;
class CreatePaymentAPIRequest extends PaymentRequest
@ -14,10 +12,7 @@ class CreatePaymentAPIRequest extends PaymentRequest
* @return bool
*/
public function __construct(InputRequest $req)
{
$this->req = $req;
}
public function authorize()
{
@ -60,22 +55,5 @@ class CreatePaymentAPIRequest extends PaymentRequest
}
public function response(array $errors)
{
/* If the user is not validating from a mobile app - pass through parent::response */
if(!isset($this->req->api_secret))
return parent::response($errors);
/* If the user is validating from a mobile app - pass through first error string and return error */
foreach($errors as $error) {
foreach ($error as $key => $value) {
$message['error'] = ['message'=>$value];
$message = json_encode($message, JSON_PRETTY_PRINT);
$headers = Utils::getApiHeaders();
return Response::make($message, 400, $headers);
}
}
}
}

View File

@ -1,6 +1,9 @@
<?php namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Request as InputRequest;
use Response;
use App\Libraries\Utils;
// https://laracasts.com/discuss/channels/general-discussion/laravel-5-modify-input-before-validation/replies/34366
abstract class Request extends FormRequest {
@ -8,6 +11,11 @@ abstract class Request extends FormRequest {
// populate in subclass to auto load record
protected $autoload = [];
public function __construct(InputRequest $req)
{
$this->req = $req;
}
/**
* Validate the input.
*
@ -48,4 +56,23 @@ abstract class Request extends FormRequest {
return $this->all();
}
public function response(array $errors)
{
/* If the user is not validating from a mobile app - pass through parent::response */
if(!isset($this->req->api_secret))
return parent::response($errors);
/* If the user is validating from a mobile app - pass through first error string and return error */
foreach($errors as $error) {
foreach ($error as $key => $value) {
$message['error'] = ['message'=>$value];
$message = json_encode($message, JSON_PRETTY_PRINT);
$headers = Utils::getApiHeaders();
return Response::make($message, 400, $headers);
}
}
}
}