Skip to content

Instantly share code, notes, and snippets.

@muath-ye
Created April 9, 2023 20:28
Show Gist options
  • Save muath-ye/32995360a766a01f8bbfb2ee180cf96f to your computer and use it in GitHub Desktop.
Save muath-ye/32995360a766a01f8bbfb2ee180cf96f to your computer and use it in GitHub Desktop.
Laravel Die and Dump for API development
<?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);
}
}
@muath-ye
Copy link
Author

muath-ye commented Apr 9, 2023

throw new \App\Exceptions\ApiException('your data goes here')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment