selam API Resources yazarken başarılı ve hata mesajını nasıl yollarız try catch kullanarak hata mesajını
return response()->json([
'data' => $data,
'status' => 'false',
'code' => 400
]);
fakat başarı mesajı nasıl yazılır.
bazı yerlerde özel olarak yazıldığını sonra çağırıldığını gördüm bu mantıklı mıdır ?
mesela
PostController
public function postPublishedByPerson(Request $request)
{
try{
$routeName = Route::currentRouteName();
$data = $this->postPublishService->publishPost($request->all(),$routeName);
return $this->responseResource->ResponseSuccess($data,"Post Published By Person successfully", ResponseAlias::HTTP_OK);
}catch (\Exception $e){
return $this->responseResource->ResponseError(null,$e->getMessage(), ResponseAlias::HTTP_INTERNAL_SERVER_ERROR);
}
}
Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Controller as BaseController;
use Symfony\Component\HttpFoundation\Response;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
/**
* @param $data
* @param string $message
* @param int $status_code
* @return \Illuminate\Http\JsonResponse
*/
public function ResponseSuccess($data, $message = "Successful", $status_code = JsonResponse::HTTP_OK)
{
return response()->json([
'status' => true,
'message' => $message,
'data' => $data
],$status_code);
}
/**
* @param $errors
* @param string $message
* @param int $status_code
* @return \Illuminate\Http\JsonResponse
*/
public function ResponseError($errors, $message = 'Data is invalid', $status_code = Response::HTTP_BAD_REQUEST)
{
return response()->json([
'status' => false,
'message' => $message,
'errors' => $errors
],$status_code);
}
}
Ayrıca bir projemde şöyle bir çözüm kullanmıştım 404 hatasını almak için
Handler.php
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
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->renderable(function (NotFoundHttpException $e, $request) {
if ($request->is('api/*')) {
return response()->json(['message' => 'Not found'], 404);
}
});
}
}