PHP code example of sfelix-martins / json-exception-handler
1. Go to this page and download the library: Download sfelix-martins/json-exception-handler library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?phprequire_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
sfelix-martins / json-exception-handler example snippets
classUserControllerextendsController{
// ...publicfunctionstore(Request $request){
// Validation
$request->validate($this->rules);
// or$this->validate($request, $this->rules);
//and or
Validator::make($request->all(), $this->rules)->validate();
if (condition()) {
// Generate response with http code and message
abort(403, 'Action forbidden!');
}
if (anotherCondition()) {
// Generate response with message and codethrownew TokenMismatchException("Error Processing Request", 10);
}
}
publicfunctionshow($id){
// If not found the default response is called
$user = User::findOrFail($id);
// Gate define on AuthServiceProvider// Generate an AuthorizationException if fail$this->authorize('users.view', $user->id);
}
namespaceApp\Exceptions;
useGuzzleHttp\Exception\ClientException;
useSMartins\Exceptions\Handlers\AbstractHandler;
classGuzzleClientHandlerextendsAbstractHandler{
/**
* Create instance using the Exception to be handled.
*
* @param \GuzzleHttp\Exception\ClientException $e
*/publicfunction__construct(ClientException $e){
parent::__construct($e);
}
}
namespaceApp\Exceptions;
useSMartins\Exceptions\JsonAPI\Error;
useSMartins\Exceptions\JsonAPI\Source;
useGuzzleHttp\Exception\ClientException;
useSMartins\Exceptions\Handlers\AbstractHandler;
classGuzzleClientHandlerextendsAbstractHandler{
// ...publicfunctionhandle(){
return (new Error)->setStatus($this->getStatusCode())
->setCode($this->getCode())
->setSource((new Source())->setPointer($this->getDefaultPointer()))
->setTitle($this->getDefaultTitle())
->setDetail($this->exception->getMessage());
}
publicfunctiongetCode(){
// You can add a new type of code on `config/json-exception-handlers.php`return config('json-exception-handler.codes.client.default');
}
}
namespaceApp\Exceptions;
useException;
useGuzzleHttp\Exception\ClientException;
useIlluminate\Foundation\Exceptions\HandlerasExceptionHandler;
useSMartins\Exceptions\JsonHandler;
classHandlerextendsExceptionHandler{
useJsonHandler;
protected $exceptionHandlers = [
// Set on key the exception and on value the handler.
ClientException::class => GuzzleClientHandler::class,
];
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.