2016-11-01 3 views
1

Slim 3 Framework를 사용하여 작은 응용 프로그램에서 사용자 정의 오류 처리기를 사용하려고합니다.Slim 3에서 미들웨어 오류 처리 사용

오류 메시지와 함께 json을 출력하고 오류 설명과 함께 메일을 보내려는 오류 클래스를 만들었습니다.

namespace App\Handlers; 

use Psr\Http\Message\ServerRequestInterface as Request; 
use Psr\Http\Message\ResponseInterface as Response; 

class CustomErrorHandlerMiddleware 
{ 

    const MAIL = "[email protected]"; 

    public function __construct($message = "", $errorCode = null) { 

     $this->message = $message; 
     $this->code = ($errorCode != null) ? $errorCode : 500; 
     $this->MailError(); 

    } 

    public function __invoke(Request $request, Response $response, $next, $msg) 
    { 
     $errorArray = ["status" => "error", "message" => $this->message]; 

     $response->withStatus($this->code)->withHeader('Content-Type','application/json')->write(json_encode($errorArray)); 

     $response = $next($request, $response); 

     return $response; 
    } 

    public function MailError() { 

     $headers = 'From: [email protected]' . "\r\n" . 
    'Reply-To: [email protected]' . "\r\n" . 
    'X-Mailer: PHP/' . phpversion(); 

     $body = "Error:\n"; 
     $body .= $this->message."\n\n"; 

     try { 
      mail(self::MAIL, "Error on localdashboards", $body, $headers); 

     } catch(Exception $e) { 
      echo $e->getMessage(); 
     } 

    } 

} 

내가 완전히 잘못했을 수도 있지만, 특정 오류가 발생하면 다른 클래스에서 이것을 호출 할 수 있습니까?

$delete = $this->db->database->delete("msn_ad_data", ["campaign_name" => $facebookData[0]["campaign_name"]]); 

    if($delete) { 

     $this->db->database->insert('msn_ad_data', [ 
      "campaign_id" => $facebookData[0]["campaign_id"], 
      "campaign_name" => $facebookData[0]["campaign_name"], 
      "impressions" => $facebookData[0]["impressions"], 
      "status" => $facebookData[1]["status"], 
      "pagename" => $facebookData[1]["bankarea"], 
      "type" => $facebookData[1]["platform"] 
     ]); 

    } else { 
     $this->app->add(new \App\Handlers\CustomErrorHandlerMiddleware("Could not save data")); 
    }´ 

을하지만 작동하지 않습니다

나는 이런 식으로 뭔가를 시도하고있다.

는 기본적으로 나는 또한 동일한 응답으로 나에게 이메일을 보내

[{ 
    "status": "error", 
    "message": "Could not save data" 
}] 

처럼 내가 할 수있는 출력은 브라우저에서, 즉 보이는 JSON과 응답을 보내려고합니다.

답변

2

미들웨어는 여기에서 올바르게 사용하지 마십시오.

class CustomException extends \Exception {} 
:

} else { 
    throw new CustomException("Could not save data"); 
} 

그런 다음 당신은뿐만 아니라 예외를 필요로 지정 ErrorHandler를

$c = new \Slim\Container(); 
$c['errorHandler'] = function ($c) { 
    return function ($request, $response, $exception) use ($c) { 
     if($exception instanceof CustomException) { 
      $message = $exception->getMessage(); // "could not save" 
      $errorCode = //$exception->getErrorCode(); when you want todo this add this as method to the exception. 
      // send mail 
      $errorArray = ["status" => "error", "message" => $message]; 

      return $response->withStatus($errorCode)->withHeader('Content-Type','application/json')->write(json_encode($errorArray)); 

     } 
     return $c['response']->withStatus(500) 
          ->withHeader('Content-Type', 'text/html') 
          ->write('Something went wrong!'); 
    }; 
}; 
$app = new \Slim\App($c); 

를 추가 : 당신은 다른 메일을 보내거나 예외를 발생 슬림의 ErrorHandler를에 처리해야