user2840318
user2840318

Reputation: 1127

Laravel - Can't handle MethodNotAllowedHttpException

I am trying to customize the MethodNotAllowedHttpException error, but I am not getting anywhere.

#app/start/global.php

App::error(function(MethodNotAllowedHttpException $exception)
{
    Response::make("Test...", 503); 
});

It just shows up a blank/empty page.

However, if I replace the MethodNotAllowedHttpException with Exception it works. But that shows up for alot of errors and I want only for this type.

Thoughts?

Upvotes: 1

Views: 3032

Answers (1)

Dan H
Dan H

Reputation: 3623

In Laravel 5, exceptions should be handled in app/Exceptions/Handler.php like so:

/**
 * Render an exception into an HTTP response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Exception  $e
 * @return \Illuminate\Http\Response
 */
public function render($request, Exception $e)
{
    if ($e instanceof ModelNotFoundException) {
        $e = new NotFoundHttpException($e->getMessage(), $e);
    }

    if ($e instanceof \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException) {
        return abort('503');
    }

    return parent::render($request, $e);
}

However, I wouldn't use 503 for these type of errors as it doesn't comply with the HTTP spec. A 405 would be more suitable if the method is not allowed for that path.

You then can create a view in resources/views/errors/405.blade.php to display something nice to the user.

Upvotes: 4

Related Questions