使用Slim 3中间件错误处理

时间:2016-11-01 08:10:37

标签: php json class slim middleware

我正在尝试使用Slim 3 Framework在我的小应用程序上使用自定义错误处理程序。

我创建了一个错误类,我想用它来输出带有错误消息的json,并发送带有错误描述的邮件。

namespace App\Handlers;

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

class CustomErrorHandlerMiddleware
{

    const MAIL = "name@domain.com";

    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: webmaster@example.com' . "\r\n" .
    'Reply-To: webmaster@example.com' . "\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"));
   }´

但它似乎不起作用。

基本上我想发送一个带有JSON的响应,我可以在浏览器中输出,看起来像

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

并发送电子邮件给我,但回复相同。

1 个答案:

答案 0 :(得分:2)

中间件在这里使用不正确。您应该只发送邮件else或抛出异常并在slim的错误处理程序中处理它:

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

你也需要例外:

class CustomException extends \Exception {}