Showing posts with label exception handler. Show all posts
Showing posts with label exception handler. Show all posts

Friday, June 16, 2017

How to Handle Laravel 5.X Exceptions

In Laravel 5.2, all errors and exceptions, both custom and default, are handled by the Handler class in app/Exceptions/Handler.php with the help of two methods ##report & ##render.

The ##report method enables you to log raised exceptions or parse them to error logging engines. 

The ##render method return with an error message as well as response code raised by any exception. It generates a HTTP response from the exception and sends it back to the browser.

We can also override the default behavior of error handling with our own custom exception handler if we need.


/**
 * 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)
{
    //$request->ajax() [[AJAX REQUEST CHECK]]
    if ($e instanceof MyException) {
        if ($request->ajax()) {
            return response()->json(['error' => 'Not Found'], 404);
        }
        return response()->view('errors.custom', [], 500);
    }
    if ($this->isHttpException($e)) {
        switch ($e->getStatusCode()) {
            case 404:
                return response()->view('errors.404', [], 500);
            case 500:
                return response()->view('errors.500', [], 500);
            default:
                return $this->renderHttpException($e);
        }
    } elseif ($e instanceof TokenMismatchException) {
        return redirect()->back()->withInput()->with('error', 'Your session has expired');
    } else {
        return response()->view('errors.500', [], 500);
    }
}

And finally you have to add a 404.blade.php && 500.blade.php file in resources/view/errors to represent our custom error page.


We can also generate a 404 as well as 500 error page response by calling the abort method which takes an optional response message.

abort(404, 'The resource you are looking for could not be found');


This will check for a related resources/view/errors/404.blade.php and serve a HTTP response with the 404 status code back to the browser. The same applies for 401 and 500 or for other error status codes.








Friday, September 20, 2013

HTTP Status Codes Handling and Htaccess ErrorDocuments

Error handling using .htacces:

Here are some basic rule, use other rules if you need.

ErrorDocument 404 /Subtitle/php/error-msg.php
ErrorDocument 500 /location/php/error-msg.php
ErrorDocument 400 /location/php/error-msg.php
ErrorDocument 401 /location/php/error-msg.php
ErrorDocument 403 /location/php/error-msg.php

And the error-msg.php like this:

Here are some basic rule, use other rules if you need.

<?php
$HttpStatus = $_SERVER["REDIRECT_STATUS"] ;
  if($HttpStatus==200) {
      echo "Document has been processed and sent to you.";      
  } else if($HttpStatus==400) {
      echo "Bad HTTP request ";      
  } else if($HttpStatus==401) {
      echo "Unauthorized - Iinvalid password";      
  } else if($HttpStatus==403) {
      echo "Forbidden";      
  } else if($HttpStatus==500) {
      echo "Internal Server Error";      
  } else if($HttpStatus==418) {
      echo "I'm a teapot! - This is a real value, defined in 1998";      
  } else if($HttpStatus==404) {
      echo "Page not found here";      
  } else {
      $HttpStatus = 500;
      echo "Internal server Error";
  }
  echo "<BR>Status: ".$HttpStatus;
  exit; 
?>

Error Distribute from php file (named: mac_address.php)

If you need to show error like above one, please see below example php code:

<?php
/* UnCaught error handler */
set_exception_handler('exc_handler');

/* Error handler function */
function exc_handler(Exception $exception) {
    /* Set http status code such 404, 500 etc. */
    header("HTTP/1.1 ".$exception->getCode()." ".$exception->getMessage());
    /**
     * As 'REDIRECT_STATUS' is using in 'error-msg.php' file,
     * so we are providing this manually.
     * But it will automatically set when come from .htaccess
     */
    $_SERVER["REDIRECT_STATUS"] = $exception->getCode();
    /**
     * Including 'error-msg.php' file.
     */
    include './error-msg.php';
}
/**
 * Extentd 'Exception' to my own class 'NotFoundException'
 */
class NotFoundException extends Exception {
    public function NotFoundException($message = "Page not found") {
        throw new Exception($message, 404);
    }
}
/**
 * Throwing 'NotFoundException'
 */
//throw new NotFoundException();

/**
 * Another way to throw exception as bellow, where 
 * 'Server error' is the message and
 * '500' is the error code.
 */
throw new Exception("Server error", 500);
?>

Example output in browser (Custom 500 error using php code):

I wrote the code in mac_address.php to show 500 internal server error.














Example output in browser (404 error using .htaccess):

No file in that location named 'mac.php', .htaccess handling this internally.