0

In Slim 3, here's an example of a custom error handler injected in the app:

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

My question is, how do I trigger this custom error?

nekosama
  • 13
  • 4

1 Answers1

1

I saw that the custom error is in container. Just call it. But I don't think you need use($c) in return function ($request, $response) use ($c) {.

Here is the example code:

<?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);
});
tirta keniten
  • 397
  • 4
  • 13