How to handle MethodNotAllowedHttpException - php

I'm looking to handle a MethodNotAllowedException. I've viewed other answers available on here that to create what i think should handle this in the exceptions/handler.php class. This is what i came up with.
public function render($request, Exception $e)
{
if ($e instanceof MethodNotAllowedHttpException) {
\Auth::logout();
\Session::flush();
return redirect()->('/')->withErrors(['error' => 'Something went wrong']);
}
return parent::render($request, $e);
}
However where i used to get an error before, all i recieve now is a blank page on the page where i usually recieve an error and a user is not logged out nor are they redirected. Am i placing this handler in the right place and if so, is the function shown below correct?
Thanks

Related

How do i redirect user to a error page when there is an error?

I would like to know how can i redirect users to an error page when there is an error with the code.
below are the error which i m trying to redirect
Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_PARSE)
syntax error, unexpected 'dd' (T_STRING)
or when a page is not valid or when there is an undefined variable
I have tried adding the following commands in app/Exceptions/Handler.php
public function render($request, Exception $exception)
{
if ($exception instanceof CustomException) {
dd('hi');
}
if ($exception instanceof ModelNotFoundException or $exception instanceof NotFoundHttpException) {
dd('hi1');
}
return parent::render($request, $exception);
}
and also have tried bellow
public function render($request, Exception $exception)
if ($this->isHttpException($exception)) {
if ($exception instanceof NotFoundHttpException) {
dd('hi2);
}
}
}
But i m still getting the error message. How can i do it so that all error will be redirected to an error page (for now i will just see the dd() instate of redirecting to the page)
Instead of dd('hi') my whole app I spend the time looking at the exception handling.
When prepending dd($e);
in the renderForConsole() method, before line
https://github.com/laravel/framework/blob/5.7/src/Illuminate/Foundation/Exceptions/Handler.php#L467
than all relevant information is printed out.
This helped me to find the error reletively fast. Maybe this is helpfull for anyone in the meantime, although it's a terrible dump of the whole application state, but was extremely helpful for me, as the stacktrace is contained.

Laravel try / catch on not working

I've searched a few questions for a reason my code is not throwing an error correctly, but I can't figure it out.
I have the following function in my controller
<?php
public function suspend($id)
{
try {
$this->collection = $this->class::find($id);
$this->collection->delete();
return $this->respond_with_success();
} catch (\Exception $e) {
return $this->respond_with_error('Failed to suspend resource with id: ' . $id);
}
}
For reference, I'm using soft deletes. I can suspend a resource once no problem. If I try to suspend one that's already suspended, Laravel correctly throws a 500 as I can see in the log file /storage/logs/laravel.log
This is part of the error I see;
local.ERROR: Call to a member function delete() on null....
Without using
withTrashed() in the query, a row quite obviously cannot be found. So this makes sense.
Great...so why does my catch not actually catch anything? I see a 500 error in the browser, but my application should allow me to continue and handle that error correctly. But it just falls over completely...
The respond_with_error function is below. I've tried changing the $code to 200 in testing, but this doesn't change anything. I've tested returning a simple string rather than with this function to no avail, so I don't think there's anything wrong with this part.
<?php
protected function respond_with_error($message = 'error', $code = 500)
{
return Response::json([
'success' => false,
'message' => $message,
], $code);
}
I'm running Laravel 5.6.29
There are two ways to address this. The first thing to note is ERROR: Call to a member function delete() on null is not an exception, it is a fatal error.
You can use findOrFail instead of find to throw an Exception when the model is not found and that will work.
You could also catch Throwable instead of Exception to catch errors and exceptions (as of PHP7) or just Error to catch errors.
As the Error hierarchy does not inherit from Exception, code that uses catch (Exception $e) { ... } blocks to handle uncaught exceptions in PHP 5 will find that these Errors are not caught by these blocks. Either a catch (Error $e) { ... } block or a set_exception_handler() handler is required.
Read more on PHP7 Error Handling here: http://php.net/manual/en/language.errors.php7.php

Laravel 5.1 prevent CSRF mismatch from throwing exception [duplicate]

This question already has answers here:
Laravel catch TokenMismatchException
(6 answers)
Closed 7 years ago.
I am getting issues with CSRF exceptions being thrown to the user. They happen for perfectly innocent reasons like if someone takes too long to fill out a form when they finally submit it the session has expired and the tokens don't match. Now obviously this is an error but it doesn't need to kill everything and throw an exception.
Is there a way to just get it to set a flash message instead and redirect back to the original page. I don't want to disable CSRF protection I just want the errors to be handled a bit more gracefully.
This is a bit of a pain, I usually add a method to the VerifyCsrfToken class to catch the TokenMismatchException (in the Middleware folder):
public function handle($request, Closure $next)
{
try
{
return parent::handle($request, $next);
}
catch(TokenMismatchException $e)
{
return redirect()->back()->withInput()->withErrors(['tokenMismatch' => 'Have you been away? Please try submitting the form again!']);
}
}
Although, you might want to tweak that depending on how you are handling errors in your app.
This can be handled in app/Handler.php
Change the render function from
public function render($request, Exception $e)
{
return parent::render($request, $e);
}
To this:
public function render($request, Exception $e)
{
if ($e instanceof \Illuminate\Session\TokenMismatchException){
return redirect($request->fullUrl())->with('error',"Sorry your session has expired please resubmit your request.");
}
return parent::render($request, $e);
}

How to show the 404 page?

I would like to show 404 page in Laravel 5 while MethodNotAllowedHttpException throws.
Can anyone help me in this regard?
Add this to app/Exceptions/Handler.php:
public function render($request, Exception $e)
{
if ($e instanceof MethodNotAllowedHttpException)
{
abort(404);
}
return parent::render($request, $e);
}
Then edit resource/views/errors/404.blade.php to personalize the page.
Simple: all you have to do is create a template at resources/views/errors/404.blade.php.
You can create views for other HTTP status codes if you’re feeling that way inclined, such as a 403.blade.php for Forbidden exceptions and so on.
I'm working on Laravel 5.2 and the answer given here worked for me.
You need to modify the render method in the app/Exceptions/Handler.php.
public function render($request, Exception $e)
{
if ($e instanceof \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException)
{
return response(view('errors.404'), 404);
}
return parent::render($request, $e);
}
abort(404) did not work for me. Looks like this method is removed in Laravel 5.
That's a 405 error, easiest way would be to create a new view in resources/views/errors/405.blade.php..
If you need fine control over what is displayed then you'll have to use the Handler.php to modify what's returned.

Simple error response in Laravel 5 while JSON request

I have project on Laravel 5, and I need to do async request via jQuery's $.ajax method.
Laravel can catch exception, and then it render special error template with it's own styles and markup.
But for async requests this html-code is redundant.
Is there a way to generate error response without laravel's markup on async requests?
I guess you wanted this to write the web service.
To handle this
Goto app/Exceptions/Handler.php :
And change this function
public function render($request, Exception $e)
{
return parent::render($request, $e);
}
to
public function render($request, Exception $e)
{
if ($this->isHttpException($e))
{
return $this->renderHttpException($e);
}
else
{
return parent::render($request, $e);
}
}
Also if you need to customize in the webview
Change your 404 blade \resources\views\errors\404.blade.php here

Categories