2016-03-17 53 views
1

我想處理苗條框架中的錯誤自定義中間件,但不知道如何做到這一點像我的代碼我這樣做,如果請求不是四種特定類型,然後通過一個錯誤我想在errorHandler中處理適當的消息和狀態,但是目前這個代碼只是在郵件回覆中的空白屏幕返回狀態。我對SLIM不太瞭解。在此先感謝Slim框架中的錯誤處理自定義中間件

<?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(); 

回答

0

拋出一個異常:

$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; 
})