Created
April 9, 2023 20:28
-
-
Save muath-ye/32995360a766a01f8bbfb2ee180cf96f to your computer and use it in GitHub Desktop.
Laravel Die and Dump for API development
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Exceptions; | |
use Exception; | |
// usage | |
// throw new \App\Exceptions\ApiException('your data goes here') | |
class ApiException extends Exception | |
{ | |
/** | |
* The attributes that handle the exception errors. | |
* | |
* @var array | |
*/ | |
protected $errors = []; | |
/** | |
* The attribute that handle the exception message | |
* | |
* @var string | |
*/ | |
protected $message = 'The given data was invalid.'; | |
/** | |
* The attribute that handle the exception status | |
* 410 [gone], 418 [I'm a teapot] | |
* | |
* @var int | |
*/ | |
protected $status = 418; | |
/** | |
* Create a new ApiException instance. | |
* | |
* @param array $errors | |
* @param string $message | |
* @return void | |
*/ | |
public function __construct($errors, $message = null, $status = null) | |
{ | |
$this->errors = $errors; | |
$this->message = is_null($message) ? $this->message : $message; | |
$this->status = is_null($status) ? $this->status : $status; | |
} | |
/** | |
* Render the exception into an HTTP response. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @return \Illuminate\Http\Response | |
*/ | |
public function render($request) | |
{ | |
return $this->json_error($this->errors, $this->status); | |
} | |
public function json_error($errors, $status = 200, array $headers = [], $options = 0) | |
{ | |
$response = $errors; | |
return response()->json($response, $status, $headers, $options); | |
} | |
} |
Author
muath-ye
commented
Apr 9, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment