Laravel has all of that built in. You can customize exception responses if needed. What is your issue exactly?
Want a reusable Laravel API error/exception/authorization handling structure.
Help me to find/suggest the better and more efficient way for handling all these cases without re writing every time.
I have found some people were using the traits and some using the Laravel built in App\Exception\Handler render function to manage the different kinds of the scenarios for the authentication, Authorization and model exception etc for to avoid writing again and again those exceptions.
I'm afraid I still don't understand what you're talking about. What needs to be rewritten again and again?
I was talking about this
<?php
namespace App\Traits;
trait ApiResponses {
protected function ok($message, $data = []) {
return $this->success($message, $data, 200);
}
protected function success($message, $data = [], $statusCode = 200) {
return response()->json([
'data' => $data,
'message' => $message,
'status' => $statusCode
], $statusCode);
}
protected function error($message, $statusCode) {
return response()->json([
'message' => $message,
'status' => $statusCode
], $statusCode);
}
}
and for auto exception handling for this
<?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* The list of the inputs that are never flashed to the session on validation exceptions.
*
* @var array<int, string>
*/
protected $dontFlash = [
'current_password',
'password',
'password_confirmation',
];
/**
* Register the exception handling callbacks for the application.
*/
public function register(): void
{
$this->reportable(function (Throwable $e) {
//
});
}
}
in the register function to handle the different types of the exception instead of writing again and again the same logic in the controller for throw an error or server error etc.
Want a reusable Laravel API error/exception/authorization handling structure.
@shivamyadav Laravel already has an exception handler that will consistently format any errors or exceptions thrown during a request. You don’t need to “handle” them at all.
Thanks 🙏
Please or to participate in this conversation.