Custom Error 500 page not displaying using Event::override - Laravel - laravel

I am able to use the Event::Override function successfully with the 404 event but not the 500 event. I simply wish the event to redirect to the front page with a flash message, as I am able to do fine with 404 events.
Is there something else I need to do to get the 500 events also redirecting to my front page? see code below in routes.php file:
Event::listen('404', function() {
return Response::error('404');
});
Event::listen('500', function() {
return Response::error('500');
});
Event::override('404', function() {
Session::flash('error', '<strong>Error 404 - Not Found.</strong> The page you are looking for is either <u>invalid</u> or <u>may no longer exist</u>. You are now back at our home page.');
return Redirect::to_route('home');
});
Event::override('500', function() {
Session::flash('error', '<strong>Error 500 - Internal Server Error.</strong> Something went wrong on our servers, apologies for that. Please contact us if this persists.');
return Redirect::to_route('home');
});
any ideas?

I've been able to work around this by updating the 500 error file directly in the \application\views\error folder.

One of my mobile application need a error as json format. I got it's solution from laravel forum . For catching http error
App::error( function(Symfony\Component\HttpKernel\Exception\HttpException $exception) {
$code = $exception->getStatusCode();
// you can define custome message if you need
return Response::json( array(
'message' => $exception->getMessage() ,
'code' => $code ,
) , $code);
});
Catch unhandled like db error, ..
App::error(function(Exception $exception , $code )
{
return Response::json( array(
'message' => $exception->getMessage() ,
'code' => $code ,
), $code );
});

Related

custom 404 Error page for backend site in laravel 5.5

I want to create custom 404 page for prefix backend. but it is only show front site 404 error page.. when backend/404-url i want to get with backend. layout 404..
Route::prefix('/backend')->group(function(){
Route::get('/test','BackController#index');
Route::get('/home','BackController#home');
Route::resources([
'categories' => 'CategoryController',
'posts' => 'PostController',
'users'=>'UserController'
]);
});
You should add/modify the render method in app/Exceptions/Handler.php to return a json response for an ajax request or a view for a normal request if the exception is one of ModelNotFoundException or NotFoundHttpException.
so your code will be look like this:
protected function renderHttpException(HttpException $e) {
$status = $e->getStatusCode();
if(Request::is('/backend/*')) { //Chane to your backend your !
return response()->view("backend/errors.{$status}", ['exception' => $e], $status, $e->getHeaders());
}else {
return response()->view("errors.{$status}", ['exception' => $e], $status, $e->getHeaders());
}
}
some links to help you achieve this:
Laravel Documentation on errors
Scoth.io tutorial for creating a 404 page using custom exception handler

Error with ajax and zf2 controller action

I was trying to use ajax to redirect to a controller action in zend framework 2 but the ajax is not responding rightly as well as I am not receiving the data alert.
Here is the ajax code:
$(".save_btn").click(function (){ //the class of submit button is save_btn
$.ajax({
type : 'POST',
url : '/template/addtemplate',
data : {'id':'test'},
success : function(data,status)
{
alert(data.message);
}
});
});
this is my controller code:
public function addtemplateAction()
{
$result = array('status' => 'error',
'message' => 'There was some error. Try again.'
);
$request = $this->getRequest();
if($request->isXmlHttpRequest()){
$data = $request->getPost();
if(isset($data['id']) && !empty($data['id'])){
return new JsonModel($result);
$result['status'] = 'success';
$result['message'] = 'We got the posted data successfully.';
}
}
return new JsonModel($result);
}
I have also added these particular things in my module.config.php file :
'strategies' => array (
'ViewJsonStrategy'
),
I think the problem lies in $request->isXmlHttpRequest() which returns blank.
Any help will be accepted..
Use any kind of developer tools. Chrome => f12 => Network tab and check your response

How can I process a Response directly in Laravel?

I'm writing code in my Laravel Controller and I want to trap some exceptions firing a response directly without returning something to the routes.
For example, I wrote a method for returning a 404 response:
public static function respondNotFound( $message = null, $instantResponse = false )
{
$message = $message ? $message : "Not Found";
$statusCode = self::STATUS_NOTFOUND;
return self::makeResponse( array( 'status' => $statusCode, 'message' => $message ), $statusCode );
}
This method calls another one for building an Illuminate Response
protected static function makeResponse( $data, $statusCode = self::STATUS_OK, $instantResponse = false )
{
$response = Illuminate\Support\Facades\Response::json( $data, $statusCode );
$response->setCallback( Input::get( 'callback' ) );
if( $instantResponse ) {
//..... I want to fire my Response here!
}
else {
return $response;
}
}
Referring to the method above, I want to specify that my response must be fired directly rather than being returned outside, avoiding a "waterfall of return".
My solution is to set up some php headers and then kill the script, but I think that it's a bit rough.
Can someone help me?
Thanks in advance.
I'm confused - why dont you just use the App::missing() filter and handle your 404 in there?
In 'app/start/global.php' add:
App::missing(function($exception)
{
if (Request::ajax())
{
return Response::json( ['status' => 'error', 'msg' => 'There was an error. I could not find what you were looking for.'] );
}
elseif ( ! Config::get('app.debug'))
{
return Response::view('errors.404', array(), 404);
}
});
From looking at your code - you seem to be duplicating the response class. I dont understand why you are doing all of that, when you can just do
return Response::view('error', $message, $statuscode);
anywhere in your application...
Edit: you could also do
App::abort(404);
And then catch the abort filter in your app. You can change the 404 to be any HTTP response code you want.

Laravel giving 404 error even though user not authenticated

I am creating an api using Laravel 4.1. I am having problem with authentication and custom errors. I want to check first if the user is authenticated and then show error message. For example localhost:8080/trips/1 is not a valid a resource; if I go to that url it giving me 404 not found error even though I am not authenticated. My point is to check the authentication first then the errors. I am using laravel http basic authentication. Here is my filter code:
Route::filter('api.auth', function()
{
if (!Request::getUser())
{
App::abort(401, 'A valid API key is required');
}
$user = User::where('api_key', '=', Request::getUser())->first();
if (!$user)
{
App::abort(401);
}
Auth::login($user);
});
Here is my custom errors:
App::error(function(Symfony\Component\HttpKernel\Exception\HttpException $e, $code)
{
$headers = $e->getHeaders();
switch ($code)
{
case 401:
$default_message = 'Invalid API key';
$headers['WWW-Authenticate'] = 'Basic realm="REST API"';
break;
case 403:
$default_message = 'Insufficient privileges to perform this action';
break;
case 404:
$default_message = 'The requested resource was not found';
break;
default:
$default_message = 'An error was encountered';
}
return Response::json(array(
'error' => $e->getMessage() ?: $default_message,
), $code, $headers);
});
Here is my routes:
Route::group(array('before' => 'api.auth'), function()
{
Route::resource('trips', 'TripController', array(
'except' => array('create', 'edit')
));
});
The error code is executing before the filters thats why I am getting 404 error instead of getting 401. Is there any way to execute filter first then the error ?
I got this issue too and the way I worked around it (though I was not a fan at all) was doing the following inside the group(s) that don't contain a route sending requests to a controller's index method:
Route::any('/', function(){});
Granted, this shouldn't be how it works, the filter should trigger no matter what.

How to use Codeigniter REST and Response method

I'm new to REST API and CURL and I've been referring to http://net.tutsplus.com/tutorials/php/working-with-restful-services-in-codeigniter-2/
If I change the error code from 403 to 200 I get the output:
'Error occured'.
If I leave the errror code as 403 I get output:
'Something has gone wrong'.
From doing some reading it seems I'm correct to give an error code of some sort but how do I pass back some more details on the error? How should I be responding?
My API
public function login_put() {
$valid = $this->membership_model->validate_username($this->put('username'));
if($valid !== TRUE){
$this->response(array('status' => 'error', 'msg' => 'error_details'), 403);
}
}
MY CURL tester
function curl_put()
{
$this->load->library('curl');
$this->curl->create('http://localhost/api/login/format/json');
$this->curl->put(array(
'username' => 'my_username'
));
$result = json_decode($this->curl->execute());
if( isset($result->status) && $result->status == 'error' ) {
echo 'Error occured';
} else {
echo 'Something has gone wrong';
}
}
Looks like you're missing a reference in your curl url. If the file where login_put is called login.php, your url should look like:
http://localhost/api/login/login/format/json
First, we have your domain, then the reference to the API. The first login referrs to the controller within the api folder and the second refers to the function name you defined (login_put)

Resources