2016-05-20 58 views
0

在斯利姆3,這裏是在應用程序中注入的自定義錯誤處理程序示例:苗條3激活的自定義錯誤處理程序

$container = new \Slim\Container(); 
$container['customError'] = function($c){ 
    return function ($request, $response) use ($c) { 
     $output = ['success'=>0, 'error'=>"Custom Error Output."]; 
     return $c['response'] 
      ->withStatus(400) 
      ->withHeader('Content-Type', 'application/json') 
      ->write(json_encode($output)); 
    }; 
}; 
$app = new \Slim\App($container); 

我的問題是,我怎麼觸發這個自定義錯誤?

回答

1

我看到自定義錯誤是在容器中。只需調用它。但我認爲您在return function ($request, $response) use ($c) {中不需要use($c)

下面是示例代碼:

<?php 

$container = new \Slim\Container(); 

$container['customError'] = function($c){ 
    return function ($request, $response) { 
     $output = ['success'=>0, 'error'=>"Custom Error Output."]; 
     return $response 
      ->withStatus(400) 
      ->withHeader('Content-Type', 'application/json') 
      ->write(json_encode($output)); 
    }; 
}; 

// init 
$app = new \Slim\App($container); 

// route 
$app->get('/error-page', function ($request, $response, $args) { 
    $customError = $this->get('customError'); 
    return $customError($request, $response); 
}); 
相關問題