The Slim Framework support forum has moved to This Tender forum is no longer maintained or monitored.

CORS and exceptions

Mike Douglas's Avatar

Mike Douglas

28 Jan, 2016 04:24 PM

Iam using a middleware which enables cors requests.
Whenever i throw an exception within my routes logic, the custom error handler gets called, but it ignores the previously set response headers from my cors middleware, leading to a cross origin request error. Iam using the default custom error handler from the docs.

class cors {
    public function __invoke($request, $response, $next) {
        $newResponse = $response->withHeader('Access-Control-Allow-Origin', '*')
                                ->withHeader('Access-Control-Allow-Headers', array('Content-Type', 'X-Requested-With', 'Authorization'))
                                ->withHeader('Access-Control-Allow-Methods', array('GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'));

        if($request->isOptions()) {
            return $newResponse;

        return $next($request, $newResponse);

  1. 1 Posted by Mike Douglas on 28 Jan, 2016 04:26 PM

    Mike Douglas's Avatar

    In addation. I solved the issue by setting the CORS header in the error handler again, but thats not such a good solution.

  2. 2 Posted by psancho.php on 16 Feb, 2016 11:22 AM

    psancho.php's Avatar

    found the cause in App.php#339 (Slim 3.1.0):
    // Traverse middleware stack
    try {
        $response = $this->callMiddlewareStack($request, $response);
    } catch (Exception $e) {
        $response = $this->handleException($e, $request, $response);

    When Exception is thrown in the stack, the catch section uses the initial Response, loosing all middleware addenda.
    Using try/catch within all middleware will not help, IMHO.

    Like you did, the only workaround I found is to mimic CORS logic directly in Exception handler, but I don't like this way.
    I hope in future version there will be a well designed solution for that.

Reply to this discussion

Internal reply

Formatting help / Preview (switch to plain text) No formatting (switch to Markdown)

Attaching KB article:


Attached Files

You can attach files up to 10MB

If you don't have an account yet, we need to confirm you're human and not a machine trying to post spam.

Keyboard shortcuts


? Show this help
ESC Blurs the current field

Comment Form

r Focus the comment reply box
^ + ↩ Submit the comment

You can use Command ⌘ instead of Control ^ on Mac