php - Error Handling in Slim Framework Custom Middleware -
i trying handle errors in slim framework custom middle ware dont know how in code doing if request not of 4 specific types through error want handel in errorhandler appropriate message , status code returning status in postman blank screen in response body. not familiar slim. in advance
<?php require 'vendor/autoload.php'; use \slim\app; $c = new \slim\container(); $c['notallowedhandler'] = function ($c) { return function ($request, $response, $methods) use ($c) { return $c['response'] ->withstatus(405) ->withheader('allow', implode(', ', $methods)) ->withheader('content-type', 'application/json') ->write(json_encode(array("c_status"=>"405","message"=>"bad request"))); }; }; $c['notfoundhandler'] = function ($c) { return function ($request, $response) use ($c) { return $c['response'] ->withstatus(404) ->withheader('content-type', 'application/json') ->write(json_encode(array("c_status"=>"404","message"=>"not found"))); }; }; $c['errorhandler'] = function ($c) { return function ($request, $response, $exception) use ($c) { $data = [ 'c_status' => $response->getstatus(), 'message' => $exception->getmessage() ]; return $container->get('response')->withstatus($response->getstatus()) ->withheader('content-type', 'application/json') ->write(json_encode($data)); }; }; $app = new app($c); $app->add(function ($request, $response, $next) { if($request->isget() || $request->ispost() || $request->isput() || $request->isdelete()){ $response = $next($request, $response); }else{ $response = $response->withstatus(403); } return $response; }); require 'api/routes.php'; $app->run();
throw exception:
$app->add(function ($request, $response, $next) { if($request->isget() || $request->ispost() || $request->isput() || $request->isdelete()){ $response = $next($request, $response); }else{ throw new \exception("forbidden", 403); } return $response; })
Comments
Post a Comment